Fix Flask app context error in SSE stream route

This commit is contained in:
2026-03-21 01:30:57 +01:00
parent 5860e4634b
commit ee0b0f3abd

35
app.py
View File

@@ -358,26 +358,29 @@ def api_download():
@login_required @login_required
def stream_download(download_id): def stream_download(download_id):
download = Download.query.get_or_404(download_id) download = Download.query.get_or_404(download_id)
download_id_val = download.id
def generate(): def generate():
last_len = 0 with app.app_context():
while True: download = Download.query.get(download_id_val)
db.session.refresh(download) last_len = 0
current_len = len(download.log) while True:
db.session.refresh(download)
if current_len > last_len: current_len = len(download.log)
new_log = download.log[last_len:]
data = f"data: {download.id}|{download.status}|{download.progress}|{new_log}\n\n" if current_len > last_len:
yield data new_log = download.log[last_len:]
last_len = current_len data = f"data: {download.id}|{download.status}|{download.progress}|{new_log}\n\n"
yield data
last_len = current_len
if download.status in ('completed', 'error'): if download.status in ('completed', 'error', 'cancelled'):
data = f"data: {download.id}|{download.status}|{download.progress}|__END__\n\n" data = f"data: {download.id}|{download.status}|{download.progress}|__END__\n\n"
yield data yield data
break break
import time import time
time.sleep(0.5) time.sleep(0.5)
return Response(generate(), mimetype='text/event-stream') return Response(generate(), mimetype='text/event-stream')