小编j2l*_*ogo的帖子

访问 Flask socketio 后台任务中的应用程序上下文

我正在使用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
Run Code Online (Sandbox Code Playgroud)

python flask flask-socketio

3
推荐指数
1
解决办法
3121
查看次数

标签 统计

flask ×1

flask-socketio ×1

python ×1