V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
Latin
V2EX  ›  Python

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

  •  
  •   Latin · 2019-12-18 18:16:19 +08:00 · 3740 次点击
    这是一个创建于 1562 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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 20:51:58 +08:00 via Android
    before_first_request 装饰器
    Latin
        2
    Latin  
    OP
       2019-12-19 09:16:49 +08:00
    @renmu 就是为了避免请求触发
    wzwwzw
        3
    wzwwzw  
       2019-12-19 09:34:30 +08:00
    如果要用 gunicorn 的话要避免多次启动这个线程。
    我目前的做法是绑定一个端口,启动 apscheduler 和 一些其他的线程。
    Latin
        4
    Latin  
    OP
       2019-12-19 11:26:14 +08:00
    @wzwwzw 主要这是个消費任务,不想放在 celery 或者 apscheduler 内跑定时 job
    15399905591
        5
    15399905591  
       2019-12-20 12:21:21 +08:00
    如果用 uwsgi 的话,单独挂载一个 mule
    slipper
        6
    slipper  
       2019-12-25 15:02:54 +08:00
    用 flask_script 这个包。继承 server 类,重写__call__方法,在这个方法里面实现你所要提前启动的代码。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2720 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:40 · PVG 23:40 · LAX 08:40 · JFK 11:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.