烧瓶应用程序启动后运行代码 [英] Run code after flask application has started
问题描述
def run():$ b $从web应用程序导入app
app.run(debug = True,use_reloader = False)
理想情况下, ():
def run():
from webapp import app
app.run(debug = True,use_reloader = False)
some_code()
但是代码不会继续app.run()直到服务器退出,所以some_code()永远不会运行
目前我正在使用的解决方案是在单独运行some_code线程从app.run(),创建一个第一次请求功能,设置此:
app.is_running = True
然后让some_code()向应用程序发出一个基本请求,以便在第一次请求之前代码运行。这是相当复杂的,将很难写文档...我宁愿参考一个已经写入烧瓶app.is_running参数,或使用@ app.after_server_start装饰器,但据我所知,这些都不存在:/
帮助我使这段代码更好?
:每当我想到这个问题,它使我想要一个 @ app.after_server_start装饰器
使用 Flask-Script 运行您的应用程序,然后覆盖像这样的runserver类/方法
#manage.py
$ b $ from flask.ext.script import经理
从myapp导入应用程序
经理=经理(应用程序)
def crazy_call():
print(crazy_call)
$ b $ manager.command $ b $ def runserver():
app.run()
crazy_call()
$ b $ if if __name__ == __main__:
manager.run()
My goal is to get arbitrary code to run after after my flask application is started, here's my issue. I've got this (where app is my flask app):
def run():
from webapp import app
app.run(debug=True, use_reloader=False)
I ideally I would just do this
def run():
from webapp import app
app.run(debug=True, use_reloader=False)
some_code()
but the code doesn't continue past app.run() until the server exits, so some_code() never runs
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
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 write docs for... I would rather refer to a app.is_running parameter already written into flask, or use a @app.after_server_start decorator, but to my knowledge neither of those exist :/
Help me make this code better ?
post humus: everytime I think about this question, it makes me want for a @app.after_server_start decorator
Use Flask-Script to run your app, then overwrite the runserver class/method like this
# manage.py
from flask.ext.script import Manager
from myapp import app
manager = Manager(app)
def crazy_call():
print("crazy_call")
@manager.command
def runserver():
app.run()
crazy_call()
if __name__ == "__main__":
manager.run()
这篇关于烧瓶应用程序启动后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!