Django视图中的异步函数

时间:2012-07-24 13:35:03

标签: python django asynchronous django-views

是否可以做这样的事情:

def new_query(request,company_uuid,address_uuid,contact_uuid):
    mcompany = get_object_or_404(Company, uuid=company_uuid)
    if request.method == 'POST': # If the form has been submitted...
        form = forms.CompanyQueryForm(request.POST)
        if form.is_valid():
            mquery = form.save(commit = False)
            mcompany = get_object_or_404(Company, uuid = company_uuid)
            mquery.company = mcompany
            mquery.version_number = 1
            mquery.parameters = {
                                    'company':company_uuid,
                                    'address':address_uuid,
                                    'contact':contact_uuid
                                    }
            mquery.save()
            preserialise(mquery.pk, company_uuid)
            recent_update = RecentUpdate(company_query=mquery, update_type="1")
            recent_update.save()
            url = reverse('view_directory',kwargs={'company_uuid':company_uuid,
                                                                'address_uuid':address_uuid,
                                                                'contact_uuid':contact_uuid})
            return HttpResponseRedirect(url)
    else:
        form = forms.CompanyQueryForm()
    return share.output_page(request,'joinerysoft/new_query.html',{'title':unicode(u'New Company Query'),
                                                                   'form': form,
                                                                   'company':mcompany,
                                                                   'address_uuid':address_uuid,
                                                                   'contact_uuid':contact_uuid})   

其中preserialise(mquery.pk, company_uuid)在后​​台运行而无需等待返回?因为预序列化需要很长时间才能完成(超过5分钟)而且我希望从用户的角度来看它是一场火灾而忘记。

2 个答案:

答案 0 :(得分:5)

您可以随时触发线程:

import threading

class PreserializeThread(threading.Thread):
    def __init__(self, mquery_pk, company_uuid, *args, **kwargs):
        self.mquery_pk = mquery_pk
        self.company_uuid = company_uuid
        super(PreserializeThread, self).__init__(*args, **kwargs)

    def run(self):
        preserialize(self.mquery_pk, self.company_uuid)

然后,将代码示例中的preserialize替换为:

PreserializeThread(mquery.pk, company_uuid).start()

另请参阅:http://docs.python.org/library/threading.html

答案 1 :(得分:2)

简单回答,不。

您的功能将在序列化完成之前完成,然后才能继续执行。

查看django-celery任务排队解决方案。