【问题标题】:Python - access flask app context before serving requestsPython - 在服务请求之前访问烧瓶应用程序上下文
【发布时间】:2021-11-27 02:17:06
【问题描述】:

用例:我有一个 python 烧瓶应用程序,它在处理路由上的任何请求之前运行 background_function()

当我执行烧瓶应用程序时,我收到错误 - RuntimeError: Working outside of application context. 我收到错误是因为我尝试在处理任何请求之前获取应用程序上下文。

在此示例中执行background_function() 的最佳pythonic 方式是什么?

from flask import Flask
from download import Download

app = Flask(__name__)

app.config.from_pyfile('config.py')

# run backgroung function
Download.background_function()

@app.route('/')
def index():
    return 'Welcome!'

if __name__ == '__main__':
    app.run()

config 文件

FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"

# Many other variables are present in this file

download 文件

from flask import current_app as app

class Download:

    @staticmethod
    def background_function():
        file_path = app.config["FILE_LOCATION"]
        # code to download file from server to local
    return

【问题讨论】:

    标签: python python-3.x flask


    【解决方案1】:

    试试这个:

    from flask import Flask
    from download import Download
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return 'Welcome!'
    
    if __name__ == '__main__':
        Download.background_function()
        app.run()
    

    download 文件

    from flask import current_app as app
    
    class Download:
    
        @staticmethod
        def background_function():
            print("testing")
    

    给定输出:

    testing
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    

    如您所见,该函数首先运行并打印testing,然后运行应用程序。

    【讨论】:

    • 试过了。它没有用。
    • 我已经修改了答案,如果可行,请告诉我,如果可行,请接受答案@here_to_learn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多