Latin
V2EX  ›  Python

如何优雅的在 FLASK 初始化 app 时提交一个后台任务?

By Latin at 2019 年 12 月 18 日 · 4603 次点击

目前做法是这样,请各位大佬指教。

thread_lock = Lock()
thread = None

def create_app():
    ...
    register_consumer(app)
    return app
    
    
def register_consumer(app):
    global thread
    if not app.debug:
        with thread_lock:
            executor = ThreadPoolExecutor(1)
            thread = executor.submit(alarmHandle, app)
6 条回复  •  2019-12-25 15:02:54 +08:00
renmu
   1
renmu  
   2019 年 12 月 18 日 via Android
before_first_request 装饰器
Latin
   2
Latin  
OP
   2019 年 12 月 19 日
@renmu 就是为了避免请求触发
wzwwzw
   3
wzwwzw  
   2019 年 12 月 19 日
如果要用 gunicorn 的话要避免多次启动这个线程。
我目前的做法是绑定一个端口,启动 apscheduler 和 一些其他的线程。
Latin
   4
Latin  
OP
   2019 年 12 月 19 日
@wzwwzw 主要这是个消費任务,不想放在 celery 或者 apscheduler 内跑定时 job
15399905591
   5
15399905591  
   2019 年 12 月 20 日
如果用 uwsgi 的话,单独挂载一个 mule
slipper
   6
slipper  
   2019 年 12 月 25 日
用 flask_script 这个包。继承 server 类,重写__call__方法,在这个方法里面实现你所要提前启动的代码。
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 33ms · 3.9.8.5