如何在 Gunicorn 启动它的主进程之前触发一个函数
How to trigger a function before Gunicorn starts it's main process
我正在 Docker 环境中使用 Gunicorn 设置 Flask 应用程序。
当我想启动我的容器时,如果我的数据库为空,我希望我的 Flask 容器创建数据库 tables(基于我的模型)。我在我的 wsgi.py 文件中包含了一个函数,但似乎每次初始化 worker 时都会触发该函数。之后,我尝试在 gunicorn.py 配置文件中使用服务器挂钩,如下所示。
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from setup import init_database
def on_starting(server):
"""Executes code before the master process is initialized"""
init_database()
def max_workers():
"""Returns an amount of workers based on the number of CPUs in the system"""
return 2 * cpu_count() + 1
bind = '0.0.0.0:8000'
worker_class = 'eventlet'
workers = max_workers()
我希望 gunicorn 会自动触发 on_starting 函数,但挂钩似乎永远不会触发。该应用程序似乎正常启动,但是当我尝试发出要插入数据库条目的请求时,它说 table 不存在。如何触发 on_starting 挂钩?
Gunicorn 导入一个模块以获取 app
(或您告诉 Gunicorn WSGI 应用程序对象所在的任何其他名称)。在导入期间,发生在 Gunicorn 开始将流量引导至应用程序之前,代码正在执行。在你创建 db
(假设你使用的是 SQLAlchemy)并导入你的模型(这样 SQLAlchemy 就会知道然后知道要创建哪些表)之后,将你的启动代码放在那里。
或者,使用预先创建的数据库填充您的容器。
我通过在创建工作程序为我的应用程序提供服务之前先预加载应用程序来解决我的问题。我通过将此行添加到我的 gunicorn.py
配置文件来做到这一点:
...
preload_app = True
这样应用程序已经 运行 并且可以接受命令来创建必要的数据库表。
我正在 Docker 环境中使用 Gunicorn 设置 Flask 应用程序。
当我想启动我的容器时,如果我的数据库为空,我希望我的 Flask 容器创建数据库 tables(基于我的模型)。我在我的 wsgi.py 文件中包含了一个函数,但似乎每次初始化 worker 时都会触发该函数。之后,我尝试在 gunicorn.py 配置文件中使用服务器挂钩,如下所示。
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from setup import init_database
def on_starting(server):
"""Executes code before the master process is initialized"""
init_database()
def max_workers():
"""Returns an amount of workers based on the number of CPUs in the system"""
return 2 * cpu_count() + 1
bind = '0.0.0.0:8000'
worker_class = 'eventlet'
workers = max_workers()
我希望 gunicorn 会自动触发 on_starting 函数,但挂钩似乎永远不会触发。该应用程序似乎正常启动,但是当我尝试发出要插入数据库条目的请求时,它说 table 不存在。如何触发 on_starting 挂钩?
Gunicorn 导入一个模块以获取 app
(或您告诉 Gunicorn WSGI 应用程序对象所在的任何其他名称)。在导入期间,发生在 Gunicorn 开始将流量引导至应用程序之前,代码正在执行。在你创建 db
(假设你使用的是 SQLAlchemy)并导入你的模型(这样 SQLAlchemy 就会知道然后知道要创建哪些表)之后,将你的启动代码放在那里。
或者,使用预先创建的数据库填充您的容器。
我通过在创建工作程序为我的应用程序提供服务之前先预加载应用程序来解决我的问题。我通过将此行添加到我的 gunicorn.py
配置文件来做到这一点:
...
preload_app = True
这样应用程序已经 运行 并且可以接受命令来创建必要的数据库表。