python - 如何从 Gunicorn 的 pre_fork Hook 访问我的应用程序?

标签 python gunicorn cherrypy

我将CherryPy与gunicorn一起使用,我需要让我的应用程序实例在主线程预 fork 上运行其init,并在 fork 后运行一些其他方法(假设我有充分的理由) - 像我这样做)。我可以安装 post_fork Hook ,但我看不到如何访问我的应用程序实例来调用该方法。

import logging

bind = '0.0.0.0:80'
workers = 3
preload_app = True
logconfig = 'logging.conf'


def post_fork(server, worker):
    logging.info('server:%s worker:%s', server, worker) 
    # How to I reach #2 in server.Server.start?   <-------- #1
import logging

import cherrypy


class Server:
    def __init__(self):
        # I need to run pre-fork
        logging.info('init')

    def start(self):
        # I need to be called post-fork  <-------- #2
        logging.info('start')

    @cherrypy.expose
    def test(self):
        return "ok"


application = cherrypy.Application(Server(), config={"global": {"environment": "embedded"}}
$ gunicorn -c config.py server:application
2019-08-14 00:42:26,033:22541:MainThread:INFO: init
2019-08-14 00:42:26,033:22541:MainThread:INFO: Starting gunicorn 19.9.0
2019-08-14 00:42:26,033:22541:MainThread:INFO: Listening at: http://0.0.0.0:80 (22541)
2019-08-14 00:42:26,033:22541:MainThread:INFO: Using worker: sync
2019-08-14 00:42:26,038:22544:MainThread:INFO: Booting worker with pid: 22544
2019-08-14 00:42:26,040:22544:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22544>
2019-08-14 00:42:26,131:22545:MainThread:INFO: Booting worker with pid: 22545
2019-08-14 00:42:26,133:22545:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22545>
2019-08-14 00:42:26,156:22546:MainThread:INFO: Booting worker with pid: 22546
2019-08-14 00:42:26,157:22546:MainThread:INFO: server:<gunicorn.arbiter.Arbiter object at 0x108f8efd0> worker:<Worker 22546>

最佳答案

经过一番尝试,我找到了答案:

def post_fork(server, worker):
    worker.app.callable.root.start()

关于python - 如何从 Gunicorn 的 pre_fork Hook 访问我的应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57486919/

相关文章:

Python/Pandas 运行总计

python - 在 start_new_thread 之后加入线程

python - 在 gunicorn 中为不同的端点配置不同的超时?

python - CherryPy 重定向到 root

Python Cherrypy 访问日志轮换

python - 尝试使用Python和BeautifulSoup来提取准确的值

python - Python 中的浮点相等处理

python - 如何根据 Flask 中的服务器变量选择配置?

python - unicorn "configuration cannot be imported"

javascript - 使用 axios 向cherrypy 函数发送 POST 请求时输入被忽略