python - 使用 Django 和 Gunicorn 在父级运行启动代码

标签 python django hook startup gunicorn

在 Django 开始监听传入连接之前,我需要在 Django 应用程序启动时运行我的代码。在第一个 HTTP 请求时运行我的代码还不够好。当我使用 Gunicorn 时,我的代码必须在父进程中运行,然后才能 fork 。

https://stackoverflow.com/a/2781488/97248在 Django 1.4.2 中似乎不起作用:在收到第一个请求之前,它不会运行中间件的 __init__ 方法。将代码添加到 urls.py 也是如此。

Google 快速搜索没有显示任何有用信息。

最佳答案

这是旧版本,但在 Gunicorn 19.0 及更高版本中,您可以创建 custom script运行您的应用程序并在其中包含您需要的启动代码。这是一个使用 Django 应用程序的示例脚本:

#!/usr/bin/env python

"""
Script for running Gunicorn using our WSGI application
"""

import multiprocessing

from gunicorn.app.base import BaseApplication

from myapp.wsgi import application  # Must be imported first


class StandaloneApplication(BaseApplication):
    """Our Gunicorn application."""

    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value for key, value in self.options.items()
            if key in self.cfg.settings and value is not None
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


if __name__ == '__main__':
    gunicorn_options = {
        'bind': '0.0.0.0:8080',
        'workers': (multiprocessing.cpu_count() * 2) + 1,
    }

    # Your startup code here

    StandaloneApplication(application, gunicorn_options).run()

关于python - 使用 Django 和 Gunicorn 在父级运行启动代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13768894/

相关文章:

Python unhash 值

Python 套接字错误弹性/解决方法

python - 如何将所有参数传递给装饰器?

python - 如何从python执行命令提示符命令

mysql - 在 GAE 中处理数据的最佳方式是什么?

python - django - 无法使用用户凭据登录

ajax - 使用 Ajax 调用更新 Django View

pthread_create 的钩子(Hook)

c - IAT Hook Internet Explorer

mercurial - 有用的 Mercurial 钩子(Hook)