【发布时间】: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