Anonymous
Flask SSE: Ответ Eventsource имеет тип MIME («Text/HTML»), который не является «текстовым/потоком событий». Прерывание с
Сообщение
Anonymous » 30 янв 2025, 10:18
Я разрабатываю бэкэнд с колбами, работающий в Google Colab, который обслуживает угловой фронт для загрузки файлов .wav и получения потока сгенерированных слов через серверные события (SSE). < /p>
Проблема:
Когда Frontend пытается подключиться к конечной точке SSE, я получаю следующую ошибку в консоли браузера: < /p>
Ответ Eventorce имеет тип MIME ("Text /html ") Это не" текст/трансляция событий ". Прерывание соединения. < /P>
Это код фронта < /p>
Код: Выделить всё
Upload
async function uploadFile() {
const fileInput = document.getElementById('fileInput');
const statusDiv = document.getElementById('status');
const outputDiv = document.getElementById('output');
if (!fileInput.files.length) {
statusDiv.textContent = "Please select a file";
return;
}
const file = fileInput.files[0];
const formData = new FormData();
formData.append("file", file);
try {
statusDiv.textContent = "Uploading...";
const response = await fetch("https:///upload", {
method: "POST",
body: formData
});
const result = await response.json();
if (response.ok) {
statusDiv.textContent = "Upload successful! Receiving text...";
const sessionId = result.session_id;
const eventSource = new EventSource(`https:///stream/${sessionId}`);
eventSource.onmessage = (e) => {
outputDiv.innerHTML += `${e.data}`;
};
eventSource.onerror = (e) => {
console.error("SSE error", e);
eventSource.close();
};
} else {
statusDiv.textContent = result.error;
}
} catch (error) {
statusDiv.textContent = "Upload failed: " + error.message;
}
}
< /code>
< /div>
< /div>
< /p>
Это бэкэнд -код < /p>
from flask import Flask, request, jsonify, Response
import os, threading, random, time, uuid, queue
from flask_cors import CORS
from pyngrok import ngrok
app = Flask(__name__)
CORS(app)
UPLOAD_FOLDER = "/content/uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
sessions = {}
WORDS = ["apple", "banana", "cherry", "dog", "elephant", "fox"]
def generate_random_words(q):
"""Generates words into a queue"""
for _ in range(10):
word = random.choice(WORDS)
q.put(word)
time.sleep(1)
q.put(None)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
file_path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(file_path)
session_id = str(uuid.uuid4())
q = queue.Queue()
sessions[session_id] = q
threading.Thread(target=generate_random_words, args=(q,)).start()
return jsonify({"session_id": session_id}), 200
@app.route('/stream/')
def stream(session_id):
def event_stream():
q = sessions.get(session_id)
if not q:
yield "event: error\ndata: Session expired\n\n"
return
while True:
word = q.get()
if word is None:
del sessions[session_id]
yield "event: end\ndata: stream ended\n\n"
break
yield f"data: {word}\n\n"
return Response(event_stream(), mimetype="text/event-stream", headers={'X-Accel-Buffering': 'no'})
def run_ngrok():
ngrok.set_auth_token("YOUR_NGROK_AUTH_TOKEN")
public_url = ngrok.connect(5000).public_url
print(f" * Public URL: {public_url}")
if __name__ == '__main__':
threading.Thread(target=run_ngrok).start()
app.run(host='0.0.0.0', port=5000)
Подробнее здесь:
https://stackoverflow.com/questions/793 ... is-not-tex
1738221531
Anonymous
Я разрабатываю бэкэнд с колбами, работающий в Google Colab, который обслуживает угловой фронт для загрузки файлов .wav и получения потока сгенерированных слов через серверные события (SSE). < /p> Проблема: Когда Frontend пытается подключиться к конечной точке SSE, я получаю следующую ошибку в консоли браузера: < /p> Ответ Eventorce имеет тип MIME ("Text /html ") Это не" текст/трансляция событий ". Прерывание соединения. < /P> Это код фронта < /p> [code] Upload async function uploadFile() { const fileInput = document.getElementById('fileInput'); const statusDiv = document.getElementById('status'); const outputDiv = document.getElementById('output'); if (!fileInput.files.length) { statusDiv.textContent = "Please select a file"; return; } const file = fileInput.files[0]; const formData = new FormData(); formData.append("file", file); try { statusDiv.textContent = "Uploading..."; const response = await fetch("https:///upload", { method: "POST", body: formData }); const result = await response.json(); if (response.ok) { statusDiv.textContent = "Upload successful! Receiving text..."; const sessionId = result.session_id; const eventSource = new EventSource(`https:///stream/${sessionId}`); eventSource.onmessage = (e) => { outputDiv.innerHTML += `${e.data}`; }; eventSource.onerror = (e) => { console.error("SSE error", e); eventSource.close(); }; } else { statusDiv.textContent = result.error; } } catch (error) { statusDiv.textContent = "Upload failed: " + error.message; } } < /code> < /div> < /div> < /p> Это бэкэнд -код < /p> from flask import Flask, request, jsonify, Response import os, threading, random, time, uuid, queue from flask_cors import CORS from pyngrok import ngrok app = Flask(__name__) CORS(app) UPLOAD_FOLDER = "/content/uploads" os.makedirs(UPLOAD_FOLDER, exist_ok=True) sessions = {} WORDS = ["apple", "banana", "cherry", "dog", "elephant", "fox"] def generate_random_words(q): """Generates words into a queue""" for _ in range(10): word = random.choice(WORDS) q.put(word) time.sleep(1) q.put(None) @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return jsonify({"error": "No file part"}), 400 file = request.files['file'] if file.filename == '': return jsonify({"error": "No selected file"}), 400 file_path = os.path.join(UPLOAD_FOLDER, file.filename) file.save(file_path) session_id = str(uuid.uuid4()) q = queue.Queue() sessions[session_id] = q threading.Thread(target=generate_random_words, args=(q,)).start() return jsonify({"session_id": session_id}), 200 @app.route('/stream/') def stream(session_id): def event_stream(): q = sessions.get(session_id) if not q: yield "event: error\ndata: Session expired\n\n" return while True: word = q.get() if word is None: del sessions[session_id] yield "event: end\ndata: stream ended\n\n" break yield f"data: {word}\n\n" return Response(event_stream(), mimetype="text/event-stream", headers={'X-Accel-Buffering': 'no'}) def run_ngrok(): ngrok.set_auth_token("YOUR_NGROK_AUTH_TOKEN") public_url = ngrok.connect(5000).public_url print(f" * Public URL: {public_url}") if __name__ == '__main__': threading.Thread(target=run_ngrok).start() app.run(host='0.0.0.0', port=5000)[/code] Подробнее здесь: [url]https://stackoverflow.com/questions/79399091/flask-sse-eventsources-response-has-a-mime-type-text-html-that-is-not-tex[/url]