如何从gunicorn的pre_fork钩子到达我的应用程序?

时间:2019-08-14 00:53:40

标签: python gunicorn cherrypy

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

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>

1 个答案:

答案 0 :(得分:0)

更多的游戏之后,我找到了答案:

def post_fork(server, worker):
    worker.app.callable.root.start()
相关问题