python进程需要时间在nginx和uwsgi上运行的django项目中启动

我正在使用
python的多处理模块开始一个过程.该过程由django项目中发送的post请求调用.当我使用开发服务器(python manage.py runserver)时,post请求不会花时间启动进程并立即完成.

我使用nginx和uwsgi在生产中部署了项目.

现在,当我发送相同的帖子请求时,完成该请求大约需要5-7分钟.它只发生在我开始进程的那些发布请求中.其他帖子请求工作正常.

这种延迟可能是什么原因?我该如何解决这个问题?

最佳答案 基本上,后台处理需要在WSGI应用程序模块之外启动.

在WSGI中,启动了一个python webapp进程来处理请求,其数量因配置而异.如果此进程生成一个新进程,该进程将阻止WSGI进程处理新请求,则在处理新请求之前使服务器阻塞并等待它完成.

我建议您使用WSGI应用程序模块中的共享队列来提供在WSGI应用程序模块之外启动的进程.像下面这样的东西.这将为webapp模块外的每个WSGI进程启动一个新处理器,以便不阻止请求.

your_app / webapp.py:

from . import bg_queue
def post():
    # Webapp POST code here
    bg_queue.add(<task data>)

your_app / processor.py:

from multiprocessing import Process

class Consumer(Process):
    def __init__(self, input_q):
        self.input_q = input_q

    def run(self):
        while True:
            task_data = input_q.get()
            <process data>

your_app / __ init__.py:

from .processor import Consumer
bg_queue = Queue()

consumer = Consumer(bg_queue)
consumer.daemon = True
consumer.start()
点赞