配置我的 Python Flask 应用每 30 秒调用一个函数

Configuring my Python Flask app to call a function every 30 seconds

我有一个 returns JSON 响应的烧瓶应用程序。但是,我希望它每 30 秒调用一次该函数,而无需单击浏览器上的刷新按钮。这是我做的

Using apscheduler

。此代码在 application.py

from apscheduler.schedulers.background import BachgroundScheduler

def create_app(config_filname):  
    con = redis.StrictRedis(host= "localhost", port=6379, charset ="utf-8", decode_responses=True, db=0)
    application = Flask(__name__)
    CORS(application)
    sched = BackgroundScheduler()

    @application.route('/users')
    @cross_origin()
    @sched.scheduled_job('interval', seconds = 20)
    def get_users():
        //Some code...
        return jsonify(users)
    sched.start()
    return application

然后在我的wsgi.py

from application import create_app
application = create_app('application.cfg')

with application.app_context():
    if __name__ == "__main__":   
        application.run()

当我 运行 这个应用程序时,我得到了 json 输出,但它在 20 秒后没有刷新而是抛出

RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context(). See the documentation for more information.

我做错了什么?如果有任何建议,我将不胜感激。

抱歉,如果这在某种程度上颠覆了问题,但如果您希望每 30 秒向用户发送一次,这可能不应该在后端完成。后端应该只在发出请求时发送数据。为了定期发送数据,需要将前端配置为定期发出请求

我个人建议使用 i 帧和 javascript 的组合来执行此操作,如堆栈溢出问题中所述: Auto Refresh IFrame HTML

最后,当涉及到您的实际代码时,这里似乎有错误:

if __name__ == "__main__":   
application.run()

“application.run()”行应该缩进,因为它在 if 语句中