如何在单独的线程中的python脚本中启动flask应用程序? [英] How to start a flask app from within a python script in a separate thread?

查看:467
本文介绍了如何在单独的线程中的python脚本中启动flask应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,它从内部服务中提取数据并将数据类型的数量存储在内存中,如下所示:

I have a script that is extracting data from an internal service and storing the count of data types in memory like this:

metrics = {
   "new_accounts": 152,
   "acquisitions": 2005,
   ...
}

这是在内存中完成的,整个过程由此脚本中的subscribe方法启动:

That is being done in memory and that whole process is kicked off by the subscribe method in this script:

if __name__ == "__main__":
    loop = asyncio.get_event_loop()

    for signal in [signal.SIGHUP, signal.SIGTERM, signal.SIGINT]:
        loop.add_signal_handler(
            signal, lambda s=signal: asyncio.create_task(close_subscriptions(s, loop)))

    for subscription in SUBSCRIPTION_TYPES:
        loop.create_task(subscribe(subscription))
    loop.run_forever()

我想通过烧瓶中的端点公开该metrics数据,以进行监视.在一个线程中,我可以像下面这样在脚本中启动flask应用吗:

I want to expose that metrics data through an endpoint in flask for monitoring purposes. In a thread, can I start the flask app in this script like this:

if __name__ == "__main__":
   ...
    for subscription in SUBSCRIPTION_TYPES:
        loop.create_task(subscribe(subscription))
    ... <start flask app in a separate thread>
    loop.run_forever()

这有意义吗?我已经在本地运行了flask应用程序,但是它无法访问此metrics数据.这是我需要解决的方法吗?

Does this make sense? I already have the flask app running locally but it doesn't have access to this metrics data. Is this the way I need to go about this?

推荐答案

尝试将指标放入队列:

https://docs.python.org/2/library/queue.html

Flask端点可以从Queue中读取所有数据,并将最后一个值公开为端点数据

Flask endpoint can read all data from Queue, and expose last value as endpoint data

欢呼,芬里尔

这篇关于如何在单独的线程中的python脚本中启动flask应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆