问题
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