python - 使用 Django 进行多处理

标签 python html multiprocessing

我使用 python 网络框架 django 制作了一个网站。在我的代码中,我创建了一个 django 表单并将其显示在 home.html 上。 django 表单从用户那里获取一个字符串值,该字符串值在 6 个函数中用作参数。 6个函数计算完结果后,结果显示在home.html上。

一切都按预期工作,但速度非常慢。慢速代码看起来像这样。

def home(request):
    form = WebForm(request.POST or None)
    context = {
        "form" : form,
    }

    if form.is_valid():
        instance = form.save(commit=False)
        string_value = form.cleaned_data.get("string_value")
        if not string_value:
            string_value = "no string value was entered"
        instance.string_value = string_value
        instance.save()

        # This is where I use the string value as a parameter in my functions

        my_func1(search)
        my_func2(search)
        my_func3(search)
        my_func4(search)
        my_func5(search)
        my_func6(search)

        # Each function in the previous 6 functions corresponds to a website.  Each function finds the first 14 images on its particular website
        # that correlate to the string value that the user submitted, and appends it to a list (my lists are img1, img2, ..., img6).
        # The below code is just setting the first 14 elements of each list in a dictionary to be used on home.html
        conf = {"form" : form}
        con1 = dict(zip_longest(('img1','img2','img3','img4','img5','img6','img7','img8','img9','img10','img11','img12','img13','img14'), img1[:14]))
        con21 = dict(zip_longest(('img21','img22','img23','img24','img25','img26','img27','img28','img29','img210','img211','img212','img213','img214'), img2[:14]))
        con31 = dict(zip_longest(('img31','img32','img33','img34','img35','img36','img37','img38','img39','img310','img311','img312','img313','img314'), img3[:14]))
        con41 = dict(zip_longest(('img41','img42','img43','img44','img45','img46','img47','img48','img49','img410','img411','img412','img413','img414'), img4[:14]))
        con51 = dict(zip_longest(('img51','img52','img53','img54','img55','img56','img57','img58','img59','img510','img511','img512','img513','img514'), img5[:14]))
        con61 = dict(zip_longest(('img61','img62','img63','img64','img65','img66','img67','img68','img69','img610','img611','img612','img613','img614'), img6[:14]))

        # Now I am combining all of the above dictionaries in to one dictionary
        context = dict(list(conf.items()) + list(con1.items()) + list(con21.items()) + list(con31.items()) + list(con41.items()) + list(con51.items()) + list(con61.items()))

    return render(request, "home.html", context)  

为了加快这个过程,我使用了多处理。这实际上确实大大加快了这个过程,我知道这一点是因为我在终端上打印正在计算的数据(数据打印速度更快)。对于多处理,我基本上删除了

    my_func1(search)
    my_func2(search)
    my_func3(search)
    my_func4(search)
    my_func5(search)
    my_func6(search)

并将其替换为

p = Process(target=my_func1, args=(search))
p.start()
p2 = Process(target=my_func2, args=(search))
p2.start()
p3 = Process(target=my_func3, args=(search))
p3.start()
p4 = Process(target=my_func4, args=(search))
p4.start()
p5 = Process(target=my_func5, args=(search))
p5.start()
p6 = Process(target=my_func6, args=(search))
p6.start()

p.join()
p2.join()
p3.join()
p4.join()
p5.join()
p6.join()

但是,此方法不会显示 home.html 上的任何数据。详细来说,当用户提交他们的字符串值时,显示的结果是单词 None。这向我暗示列表 img1, img2, ..., img6 是空的,但我知道调用 6 个函数的多处理代码确实有效,所以我很困惑。

此外,我的 home.html 页面上的代码看起来像这样

# In home.html (I am going to add pseudo code to save me some time)

Code to display the form is here

 all of my image elements are displayed like this
 <h1>{{ img1 }}</h1>

谁能帮我解决这个问题,我将不胜感激。谢谢。

最佳答案

您似乎没有取回数据的原因是您正在生成子进程来执行任务,但子进程不会通知父进程他们产生了什么结果。

你应该考虑this documentation sample关于在进程之间共享状态并对其进行调整以共享子进程中产生的结果。

引用上面文档链接中的代码片段:

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

请注意,这并不是真正的 django 特定细节。这只是关于进程间通信,通常应该有用。

更新

此次更新是为了解决您在下方评论部分提出的一些问题。

I don't understand what the phrase that starts with if name == 'main' is doing.

if __name__ == '__main__' 不是赋值,它是用于防止意外代码执行的比较(注意双 == 而不是单个 =)。每当您直接启动 Python 模块时,其名称将为 '__main__' 并将按预期运行,但当它是从不同的模块导入时(例如使用 pydoc3) ,那么 __name__ 将不同并且检查将失败,从而阻止程序实际运行,这正是您想要的。

It is assigning num as a double with an initial value of 0.0, and arr as an array with integer elements that are range(10).

文档是你的 friend :

它是用来回答这类问题的:)

Also, how would I initiate an array with string 14 string elements? Would this work arr = Array('string', len(14))?

这是行不通的,因为 len 函数需要一个序列或集合,而您发送的是一个标量值(即 14)。

我建议您编写一个简短的测试程序,看看它们是如何工作的。我认为那样学习更有效。例如:

>>> from multiprocessing import Array
>>> a = Array('i', 3)    # Array of integers with 3 elements
>>> for i in a: print(i)
...
0
0
0
>>>

PS:我已经删除了我之前的评论,这些评论是此次更新的基础。

关于python - 使用 Django 进行多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32409344/

相关文章:

python Pandas : NameError: name is not defined

javascript - 检查 Javascript 中文本区域输入时的按键事件监听器

python - dask.delayed 导致没有加速

python - 事件期间GUI没有变化吗? (Python3.6、PyQt5)

python - 与 Pandas 的参差不齐的转置

html - 我的网页有很多不必要的空格,我该如何解决?

python - 多处理池是否为每个进程提供相同数量的任务,或者它们是否被分配为可用?

python - 使用多处理 append 到同一列表 - python

python - 获取 ServerDisconnectedError 异常,Connection.release() 会帮助解决这个问题吗?

php - 结果未正确输入 SQL DB