20

I'm using Flask/Gunicorn to run a web application and have a question about the lifecycle management. I have more experience in the Java world with servlets.

I'm creating a restful interface to a service. The service is always running on the server and communicates and controls with a set of sub-servers. In Java, my service would be created and initialized (e.g. the setup traditionally found in main()) through listeners and servlet initialization methods.

Where would the equivalent setup and configuration be in Flask? I'm thinking of tasks like creating a database connection pool, sending hello messages to the sub-servers, resetting the persisted system state to initial values, etc.

Would that go in the before_first_request method of Flask?

Based on @Pyrce's comments I think I could create a main.py:

app = Flask(your_app_name)

#initialization code goes here

and then run with:

>gunicorn main:app

Pace
  • 41,875
  • 13
  • 113
  • 156

1 Answers1

25

You can still use the same main() method paradigm. See this starter code below:

app = Flask(your_app_name) # Needs defining at file global scope for thread-local sharing

def setup_app(app):
   # All your initialization code
setup_app(app)

if __name__ == '__main__':
    app.run(host=my_dev_host, port=my_dev_port, etc='...')

The before_first_request method could also handle all of those items. But you'll have the delay of setup on first request rather than on server launch.

Pyrce
  • 8,296
  • 3
  • 31
  • 46
  • 2
    Actually, on second thought, won't that just run the development server and not WSGI? – Pace Mar 07 '14 at 20:40
  • Unless I am misunderstanding your question, no. It does depend on what you're using to manage the server, but from the docs "Just remember that your Flask application object is the actual WSGI application." – Pyrce Mar 07 '14 at 21:25
  • 1
    It does depend somewhat in that you won't have access to the main method in running Gunicorn. I suppose I can put that code in a root module that doesn't check if `__name__ == '__main__'`. I'll update my question with an example of what I'm thinking. Does it seem right to you? – Pace Mar 07 '14 at 21:33
  • Ah yes I know exactly what you mean now. For launching with guinicorn if there's setup that guinicorn can't be configured for then you just need to run setup on the application so it's ready to run. Edited answer to reflect that. – Pyrce Mar 07 '14 at 21:56
  • If I understand correctly then the function setup_app is where we will initialise, and will it be called just once when the server is started? – arqam Nov 22 '18 at 08:58
  • 3
    I doubt that this solution will work when you wrap the flask app with a production application server such as uwsgi. The flask “app” object is passed to uwsgi, and the object does not have the setup_app function in its scope. – CraigDavid Jun 28 '19 at 06:45