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
lispmacro
V2EX  ›  Python

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

  •  
  •   lispmacro · 2017-07-31 16:51:46 +08:00 · 2336 次点击
    这是一个创建于 2461 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 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 条回复    2017-07-31 18:58:28 +08:00
    wellsc
        1
    wellsc  
       2017-07-31 16:56:54 +08:00   ❤️ 1
    写个启动函数,在 if __name__ == "__main__": 里面调用
    ryd994
        2
    ryd994  
       2017-07-31 17:34:55 +08:00   ❤️ 1
    你这样混着当然不行

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

    如果需要性能 /更复杂,用队列,比如 celery。另外启动后端处理
    CryMeatel
        3
    CryMeatel  
       2017-07-31 18:58:28 +08:00   ❤️ 1
    多线程 /多进程异步掉~ 如果需求更复杂,上 Celery 等工具吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   916 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:29 · PVG 05:29 · LAX 14:29 · JFK 17:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.