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

2024-04-19 09:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的函数,它遍历一个url列表,使用GET检索一些信息并相应地更新DB(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以获取信息,并更新DB。

我唯一能找到的就是用芹菜,但对于我想完成的简单任务来说,这似乎有点力不从心。

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


Tags: 函数fromip信息url列表dbget
3条回答

我建议对多线程解决方案使用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)

尽管使用芹菜看起来有点过头了,但它是一种众所周知的异步任务处理方法。本质上,Django服务于WSGI请求-响应周期,它对多处理或后台任务一无所知。

以下是可选方案:

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

这意味着响应时间对您来说无关紧要,如果您的响应时间减少了4(使用4个子进程/线程),那么您可以在前台执行,而不是在后台(异步)执行。如果是这种情况,您可以简单地将示例代码放在视图中。就像

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")

但是,如果你想在后台异步完成,那么你应该使用芹菜或者遵循@BasicWolf的建议之一。

相关问题 更多 >