我正在使用 Flask-SocketIO 库开发 Flask 应用程序,以实现服务器后台任务与客户端之间的实时通信。
我需要在后台任务中访问我的数据库,我不知道如何实现它,因为没有初始化应用程序上下文。
我的代码是:
@socketio.on('connect', namespace='/rt/notifications/')
def start_notifications_thread():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=notifications_job)
def notifications_job():
last_alert_id = None
while True:
socketio.sleep(60)
last_id = Alert.get_last_alert_id() # Flask-SQLAlchemy model
if last_alert_id is not None and last_id != last_alert_id:
socketio.emit('new_alerts', {'msg': 'New alert', 'id': last_id}, namespace='/rt/notifications/')
last_alert_id = last_id
答案 0 :(得分:1)
根据flask-socketio的作者 miguelgrinberg ,以下是正确的方法。简单地说,我必须将我的应用实例传递给notifications_job
方法,如下所示:
from threading import Lock
from flask import current_app
from .. import socketio
thread = None
thread_lock = Lock()
def notifications_job(app):
last_alert_id = None
with app.app_context():
while True:
socketio.sleep(60)
last_id = Alert.get_last_alert_id() # Flask-SQLAlchemy model
if last_alert_id is not None and last_id != last_alert_id:
socketio.emit('new_alerts', {'msg': 'New alert', 'id': last_id}, namespace='/rt/notifications/')
last_alert_id = last_id
@socketio.on('connect', namespace='/rt/notifications/')
def start_notifications_thread():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(notifications_job, current_app._get_current_object())