本文介绍了使用Django和Gunicorn在父级中运行启动代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need my code run at Django application startup, before Django starts listening for incoming connections. Running my code upon the first HTTP request is not good enough. When I use Gunicorn, my code must run in the parent process, before it forks.

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

https://stackoverflow.com/a/2781488/97248 doesn't seem to work in Django 1.4.2: it doesn't run the Middleware's __init__ method until the first request is received. Ditto for adding code to urls.py.

快速的Google搜索没有发现任何有用的信息.

A quick Google search didn't reveal anything useful.

推荐答案

这很旧,但在Gunicorn 19.0及更高版本中,您可以创建自定义脚本来运行您的应用程序,并在其中包含所需的启动代码.这是使用Django应用程序的示例脚本:

This is old but in Gunicorn version 19.0 and above, you can create a custom script to run your application and include the startup code that you need there. Here is an example script using a django app:

#!/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()

这篇关于使用Django和Gunicorn在父级中运行启动代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:07
查看更多