在flask应用程序启动后运行代码 [英] Run code after flask application has started
问题描述
我的目标是在我的 Flask 应用程序启动后运行任意代码.这是我所拥有的:
My goal is to get arbitrary code to run after my Flask application is started. Here is what I've got:
def run():
from webapp import app
app.run(debug=True, use_reloader=False)
理想情况下,我可以这样做:
Ideally I would be able to just do this:
def run():
from webapp import app
app.run(debug=True, use_reloader=False)
some_code()
但是代码不会继续超过 app.run()
,所以 some_code() 永远不会运行.
But the code doesn't continue past app.run()
, so some_code() never runs.
我目前正在研究的解决方案是在与 app.run() 不同的线程中运行 some_code(),创建一个 在第一个请求之前 设置这个的函数:
The solution I'm working on at the moment is to run some_code() in a separate thread from app.run(), create a before first request function that sets this:
app.is_running = True
然后使用 some_code() 向应用程序发出基本请求,以便运行第一个请求之前"代码.这是相当复杂的,将难以记录.我宁愿使用 Flask 中已经提供的 app.is_running 参数,或者使用 @app.after_server_start
装饰器,但据我所知,这两个都不存在.
Then get some_code() to shoot a basic request to app so that the 'before first request' code runs. This is fairly convoluted and going to be hard to document. I would rather use app.is_running parameter which already is provided in Flask, or use a @app.after_server_start
decorator, but to my knowledge neither of those exists.
帮我改进这段代码?
Posthumous:每次想到这个问题,我都希望有一个 @app.after_server_start
装饰器存在.
Posthumous: Every time I think about this issue, it makes me wish that a @app.after_server_start
decorator existed.
推荐答案
如果你需要在你的flask应用程序启动之后但严格在第一个请求之前执行一些代码,甚至不会被第一个请求的执行触发@app.before_first_request 可以处理,你应该使用 Flask_Script,正如 CESCO 所说,但你可以将类 Server 子类化并覆盖 __ call __ 方法,而不是用@manager.command 覆盖 runserver 命令:
If you need to execute some code after your flask application is started but strictly before the first request, not even be triggered by the execution of the first request as @app.before_first_request can handle, you should use Flask_Script, as CESCO said, but you could subclass the class Server and overwrite the __ call __ method, instead of overwriting the runserver command with @manager.command:
from flask import Flask
from flask_script import Manager, Server
def custom_call():
#Your code
pass
class CustomServer(Server):
def __call__(self, app, *args, **kwargs):
custom_call()
#Hint: Here you could manipulate app
return Server.__call__(self, app, *args, **kwargs)
app = Flask(__name__)
manager = Manager(app)
# Remeber to add the command to your Manager instance
manager.add_command('runserver', CustomServer())
if __name__ == "__main__":
manager.run()
这样您就不会覆盖 runserver 命令的默认选项.
This way you don't override default options of runserver command.
这篇关于在flask应用程序启动后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!