1

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.

Konrad
  • 852
  • 11
  • 31

1 Answers1

-2

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.

Daniel Collins
  • 752
  • 3
  • 14
  • Thanks for your reply. I don't understand how this solves the issue: the documentation doesn't mention anything related to my question as to its goals. It seems the goal is to be able to instanciate multiple Flask apps with different parameters. Could you kindly explain further? – Konrad Feb 11 '19 at 20:06
  • This was correctly marked as a duplicate. If you have a global variable with a subscriber client instantiated, you will only ever have one instance of that subscriber. If you make sure in your create_app function that you import that file, you can ensure that the subscriber is created before your flask app starts. – Daniel Collins Feb 12 '19 at 18:11
  • @DanielCollins, can share some example? I am also in similar requirement. – Praveen Nov 16 '22 at 23:12