Shared object across threads in Flask [duplicate]

和自甴很熟 提交于 2019-12-25 18:41:06

问题


I have a Web server that runs a Flask app.

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.

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

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/54637324/shared-object-across-threads-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!