如何在 Django 视图中使用 python 多处理模块

How to use python multiprocessing module in django view

我有一个简单的函数,它遍历 URL 的列表,使用 GET 检索一些信息并相应地更新数据库 (PostgresSQL)。该功能完美运行。但是,一次过一遍 URL 讲太多时间。

使用 python,我可以执行以下操作来并行完成这些任务:

from multiprocessing import Pool

def updateDB(ip):
     code goes here...

if __name__ == '__main__':
    pool = Pool(processes=4)              # process per core
    pool.map(updateDB, ip)

这工作得很好。但是,我试图找到如何在 django 项目上做同样的事情。目前我有一个函数(视图)遍历每个 URL 以获取信息并更新数据库。

我唯一能找到的就是使用 Celery,但这对于我想要执行的简单任务来说似乎有点过分了。

有什么简单的我可以做的或者我必须使用芹菜吗?

尽管使用 Celery 似乎有点矫枉过正,但它是执行异步任务的一种众所周知的方式。本质上,Django 服务于 WSGI 请求-响应循环,它对多处理或后台任务一无所知。

以下是备选方案:

Currently I have a function (view) that go over each URL to get the information, and update the DB.

这意味着响应时间对你来说并不重要,而不是在后台(异步),如果你的响应时间减少 4(使用 4 sub-processes/threads).如果是这种情况,您只需将示例代码放在视图中即可。喜欢

from multiprocessing import Pool

def updateDB(ip):
     code goes here...

def my_view(request):
    pool = Pool(processes=4)              # process per core
    pool.map(updateDB, ip)
    return HttpResponse("SUCCESS")

但是,如果您想在后台异步执行此操作,那么您应该使用 Celery 或遵循@BasicWolf 的建议之一。

我建议使用 gevent 作为多线程解决方案而不是多处理。多处理可能会在产生新进程受限的生产环境中引起问题。

示例代码:

from django.shortcuts import HttpResponse
from gevent.pool import Pool

def square(number):
    return number * number

def home(request):
    pool = Pool(50)
    numbers = [1, 3, 5]
    results = pool.map(square, numbers)
    return HttpResponse(results)