Flask中跨线程共享对象 [英] Shared object across threads in Flask

查看:244
本文介绍了Flask中跨线程共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行Flask应用程序的Web服务器.

I have a Web server that runs a Flask app.

我还需要使用拉"策略实现Google pub/sub订阅者.这基本上意味着我必须实例化一个订户,该订户将不断轮询其订阅中的消息.找到消息后,它将调用一个函数.

I also need to implement a Google pub/sub subscriber, using a "Pull" strategy. This basically means I have to instanciate a subscriber, which will constantly poll for messages from its subscription. When it finds a message, it calls a function.

当前,我混合了所有内容:我的app.py脚本及其端点和订阅者的实例.

Currently, I have everything mixed in: my app.py script with its endpoints and the instanciation of the subscriber.

我不确定的是:我可以确定只有一个订户被实例化了吗?基本上,app.py什么时候执行?我一直试图从Flask文档中找出答案,但不介意一些见识.

What I am unsure about is: can I be sure that there will only be one subscriber instanciated? Basically, when does app.py get executed? I have been trying to figure this out from the Flask docs but wouldn't mind some insights.

真正的问题是:我如何拥有Flask Web服务器并正确实例化订户?

And the real question is: how can I have a Flask web server AND instanciate my subscriber correctly?

编辑有关可能重复"的问题: 我不认为这是重复的:尽管我在发布此问题之前已经看过这个问题,并且它给了我很多信息,但它的重点是将变量存储在数据库中,而不是作为全局变量.我的问题不同:我需要使该对象连续运行,所以我必须找到一种使它工作的方法.

Edit about "Possible duplicate" issue: I don't believe this is a duplicate: while I have looked at this question before posting this and it gave me good information, it was focused on storing variables in a database instead of as global variables. My problem is different: I need to have this object running continuously so I have to find a way to make it work.

推荐答案

我建议您看看烧瓶的工厂

I would suggest that you take a look at flask's factory documentation for the preferred way to do this. Essentially, have your subscriber instantiated at global scope in a separate file, and import that file inside of your create_app function and wherever else it is needed.

这篇关于Flask中跨线程共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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