简体   繁体   English

在flask / gunicorn中初始化应用的地方

[英]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. 我正在使用Flask / Gunicorn来运行Web应用程序,并对生命周期管理提出疑问。 I have more experience in the Java world with servlets. 我在使用servlet的Java世界中有更多的经验。

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 (eg the setup traditionally found in main() ) through listeners and servlet initialization methods. 在Java中,我的服务将通过监听器和servlet初始化方法创建和初始化(例如传统上在main()找到的设置main()

Where would the equivalent setup and configuration be in Flask? 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. 我正在考虑创建数据库连接池,向子服务器发送hello消息,将持久化系统状态重置为初始值等任务。

Would that go in the before_first_request method of Flask? 那会是Flask的before_first_request方法吗?

Based on @Pyrce's comments I think I could create a main.py : 基于@Pyrce的评论,我想我可以创建一个main.py

app = Flask(your_app_name)

#initialization code goes here

and then run with: 然后运行:

>gunicorn main:app

You can still use the same main() method paradigm. 您仍然可以使用相同的main()方法范例。 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. before_first_request方法也可以处理所有这些项目。 But you'll have the delay of setup on first request rather than on server launch. 但是你会在第一次请求而不是服务器启动时延迟设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM