问题
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})
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.
回答1:
You can always fire off a thread:
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)
Then, replace preserialize
in your code sample with:
PreserializeThread(mquery.pk, company_uuid).start()
See also: http://docs.python.org/library/threading.html
回答2:
Simple answer, no.
Your function will take until serialization is finished before continuing execution.
Have a look at django-celery for a task queuing solution.
来源:https://stackoverflow.com/questions/11632034/async-functions-in-django-views