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

标签 python django nginx process uwsgi

我正在使用 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()

关于运行在nginx和uwsgi上的django项目中python进程启动需要时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38891879/

相关文章:

python - 从关闭的文件中返回生成器 | csv 阅读器不返回生成器作为 openpyxl?

python - 需要 Django python 帮助

python - 值错误 : must have exactly one of create/read/write/append mode

python - 使用 Django 进行 App Engine 模型过滤

python - 从两列计算和创建百分比列

python - Django -objects.all() 不显示任何内容

Django 表单 'autocomplete' ='off' 不起作用

ruby-on-rails-3 - Rails nginx 目录索引被禁止

api - 如何动态获取 NGINX 代理的 API 访问 token

nginx 500 内部服务器错误