From 225d874c05a0d3ee92a1fad2ff7ab0623d12c7b4 Mon Sep 17 00:00:00 2001 From: NguyenND Date: Fri, 17 Apr 2026 15:15:22 -0400 Subject: [PATCH] 04/17 Update: fixed email ingestion ticket error 2 --- app/services/notification_service.py | 32 +++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/app/services/notification_service.py b/app/services/notification_service.py index dd5d6ba..82058b0 100644 --- a/app/services/notification_service.py +++ b/app/services/notification_service.py @@ -89,14 +89,36 @@ def create_notification(user_id, notif_type, title, message, ticket_id=None, lin 'link' : link, 'created_at': notif.created_at.isoformat(), } - def _emit(): + # Emit strategy depends on whether we have a live request context: + # + # - Inside a web request → use start_background_task() so the emit + # runs in eventlet's green-thread pool and does not block the WSGI + # response or race with a polling->WebSocket upgrade handshake. + # + # - Outside a request context (e.g. APScheduler background job) -> + # call socketio.emit() directly. start_background_task() causes + # Flask-SocketIO to invoke the on_connect handler internally, which + # references current_user -- but there is no session to resolve it + # from, so Flask-Login returns None and raises AttributeError. + # A direct emit bypasses that handler entirely and is safe from a + # background thread that already has an app context active. + from flask import has_request_context + if has_request_context(): + def _emit(): + socketio.emit( + 'new_notification', + payload, + to=f'user_{user_id}', + namespace='/', + ) + socketio.start_background_task(_emit) + else: socketio.emit( 'new_notification', payload, - to=f'user_{user_id}', # 'to' is the modern alias for 'room' - namespace='/', # explicit default namespace — avoids - ) # ambiguity under reverse-proxy setups - socketio.start_background_task(_emit) + to=f'user_{user_id}', + namespace='/', + ) except Exception as exc: db.session.rollback()