推荐学习书目
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 · Dec 18, 2019 · 4309 views
    This topic created in 2342 days ago, the information mentioned may be changed or developed.

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

    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 replies    2019-12-25 15:02:54 +08:00
    renmu
        1
    renmu  
       Dec 18, 2019 via Android
    before_first_request 装饰器
    Latin
        2
    Latin  
    OP
       Dec 19, 2019
    @renmu 就是为了避免请求触发
    wzwwzw
        3
    wzwwzw  
       Dec 19, 2019
    如果要用 gunicorn 的话要避免多次启动这个线程。
    我目前的做法是绑定一个端口,启动 apscheduler 和 一些其他的线程。
    Latin
        4
    Latin  
    OP
       Dec 19, 2019
    @wzwwzw 主要这是个消費任务,不想放在 celery 或者 apscheduler 内跑定时 job
    15399905591
        5
    15399905591  
       Dec 20, 2019
    如果用 uwsgi 的话,单独挂载一个 mule
    slipper
        6
    slipper  
       Dec 25, 2019
    用 flask_script 这个包。继承 server 类,重写__call__方法,在这个方法里面实现你所要提前启动的代码。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6320 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 02:23 · PVG 10:23 · LAX 19:23 · JFK 22:23
    ♥ Do have faith in what you're doing.