有没有办法先 return 响应,但在响应后仍然做其他事情?姜戈

is there a way to return a response first but still does something else after the response? django

我想 return 首先在 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})

所以我想知道是否有机会 return 先回复?以上是我的意思的一个例子。

我不确定这是否可以在 django 中完成,如果可能的话,有人可以告诉我谁可以完成吗

提前致谢。

好吧,这更像是 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})

这里的想法是将您想要 运行 的代码异步提取到函数中,然后 运行 它们在一个线程中。