Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

python - Where in flask/gunicorn to initialize application

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...