Flask-SQLAlchemy 的 Flask-socketio 上下文

2 flask flask-sqlalchemy flask-socketio

我正在使用 Flask、Flask-Socketio 和 Flask-SQLAlchemy 创建实时报告应用程序。我当前的设计在连接上创建一个后台线程,用于查询 API 并插入到应用程序数据中。但是,当运行这个时,我收到错误

RuntimeError: No application found. Either work inside a view function or push an application context.

Flask_react_app.py:

from threading import Lock
from flask import Blueprint, render_template
from .model import Stock
from . import socketio

main = Blueprint('main', __name__)
thread_lock = Lock()
thread = None


@main.route('/')
def index():
    """Serve client-side application."""
    return render_template('index.html', async_mode=socketio.async_mode)


def generate_data():
    """
    returns the Stock object query set
    """
    return [i.serialize for i in Stock.query.all()]


def background_thread():
    """Example of how to send server generated events to clients."""
    while True:
        socketio.sleep(10)
        socketio.emit("my_response", generate_data())


@socketio.on("connect")
def test_connect():
    """
    Connect method which fires off thread to notify worker to get data.
    :return: emits initial data.
    """

    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)
    socketio.emit("my_response", generate_data())
Run Code Online (Sandbox Code Playgroud)

我对此有两个问题。首先提到的bug,其次肯定有更好的办法!

Mig*_*uel 6

您的问题与 Flask-SocketIO 无关,而是与以下事实有关:要在后台线程中使用 Flask-SQLAlchemy,您需要一个应用程序上下文。

请尝试以下操作:

def background_thread(app):
    """Example of how to send server generated events to clients."""
    with app.app_context():
        while True:
            socketio.sleep(10)
            socketio.emit("my_response", generate_data())
Run Code Online (Sandbox Code Playgroud)

然后在启动后台线程的地方将应用程序实例作为参数传递:

thread = socketio.start_background_task(target=background_thread, args=(current_app._get_current_object(),))
Run Code Online (Sandbox Code Playgroud)