gpt4 book ai didi

python-3.x - 如何在 Gunicorn 启动其主进程之前触发函数

转载 作者:行者123 更新时间:2023-12-02 22:37:16 31 4
gpt4 key购买 nike

我正在 Docker 环境中使用 Gunicorn 设置 Flask 应用程序。

当我想要启动容器时,如果数据库为空,我希望 Flask 容器创建数据库表(基于我的模型)。我在 wsgi.py 文件中包含了一个函数,但这似乎在每次初始化工作进程时都会触发该函数。之后,我尝试在 Gunicorn.py 配置文件中使用服务器 Hook ,如下所示。

"""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函数,但钩子(Hook)似乎永远不会触发。该应用程序似乎正常启动,但是当我尝试发出想要插入数据库条目的请求时,它说该表不存在。如何触发 on_starting Hook ?

最佳答案

我通过在创建工作人员来为我的应用程序提供服务之前先预加载应用程序来解决我的问题。我通过将此行添加到我的 gunicorn.py 配置文件中来做到这一点:

...
preload_app = True

这样应用程序就已经在运行并且可以接受命令来创建必要的数据库表。

关于python-3.x - 如何在 Gunicorn 启动其主进程之前触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610881/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com