我想首先在django视图中返回一个响应,然后在响应之后做一些事情。
我们说我有这样的例子......
class Res(View):
def post(self, request):
data = request.POST
new_obj = Model.objects.create(name=data.['name'])
# what is below does not have to be done RIGHT AWAY, can be done after a response is made
another_obj = Another()
another_obj.name = new_obj.name
another_obj.field = new_obj.field
another_obj.save()
# some other looping and a few other new models to save
return JsonResponse({'status': True})
所以我想知道是否有机会首先返回响应?上面的内容是我的意思的一个例子。
我不确定这是否可以在django中完成,如果可能,有人可以告诉我这可以做到的事情
提前致谢。
答案 0 :(得分:2)
嗯,这更像是一个Python而不是Django的问题。正如评论所指出的那样,您可以实现某种类似Celery的异步队列,但这对您的用例来说可能有点过分。
请考虑使用普通Python threads:
from threading import Thread
def create_another_obj(name, field):
another_obj = Another()
another_obj.name = name
another_obj.field = field
another_obj.save()
class Res(View):
def post(self, request):
data = request.POST
new_obj = Model.objects.create(name=data['name'])
# start another thread to do some work, this is non-blocking
# and therefore the JsonResponse will be returned while it is
# running!
thread = Thread(
target=create_another_obj,
args=(new_obj.name, new_obj.field),
)
thread.start()
return JsonResponse({'status': True})
这里的想法是将要异步运行的代码提取到函数中并在线程中运行它们。