推荐学习书目
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
lispmacro
V2EX  ›  Python

如何在 flask 启动的时候同时也顺带启动其他 Python 代码

  •  
  •   lispmacro · Jul 31, 2017 · 3263 views
    This topic created in 3243 days ago, the information mentioned may be changed or developed.

    用 flask 写了几个 restful 接口, 同时我又有一段 rabbitmq 的消息消费代码, 我想把 rabbitmq 的消息消费代码放到 flask 中, 随 flask 启动应该怎么搞?

    if __name__ == '__main__':
        app.run()
        msg_comsue)
    

    上面这种方式不行, 因为我是用 tornado 来调 app 的.

    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop
    from run import app
    
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(5000) 
    IOLoop.instance().start()
    
    3 replies    2017-07-31 18:58:28 +08:00
    wellsc
        1
    wellsc  
       Jul 31, 2017   ❤️ 1
    写个启动函数,在 if __name__ == "__main__": 里面调用
    ryd994
        2
    ryd994  
       Jul 31, 2017   ❤️ 1
    你这样混着当然不行

    tornardo 假设你的代码就是个干净的无状态的 web app,取决于你的设置,可能多线程或多进程跑。
    嵌的 msg_consume 要防止竞态就需要跨进程通讯,这会很恶心
    建议分离出来,我猜 msg_comsue 就是隔段时间检查是吧,做个 /msg_comsue 请求触发相应函数,做好安全限制本地访问,然后 cron 访问就好

    如果需要性能 /更复杂,用队列,比如 celery。另外启动后端处理
    CryMeatel
        3
    CryMeatel  
       Jul 31, 2017   ❤️ 1
    多线程 /多进程异步掉~ 如果需求更复杂,上 Celery 等工具吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5245 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 03:45 · PVG 11:45 · LAX 20:45 · JFK 23:45
    ♥ Do have faith in what you're doing.