Django视图中的异步函数 [英] Async functions in Django views

查看:181
本文介绍了Django视图中的异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以执行以下操作:

Is it possible to do something like this:

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分钟),所以我希望它能引起用户的注意,并引起用户的注意.

where preserialise(mquery.pk, company_uuid) runs in the background without waiting to return? as pre-serialisation takes a long time to complete (over 5 minutes) and I'd like it to be a fire and forget from the perspective of the user.

推荐答案

您始终可以触发线程:

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 替换为:

Then, replace preserialize in your code sample with:

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

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

这篇关于Django视图中的异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆