将Django请求对象传递给芹菜任务

发布于 2021-01-29 14:11:12

我在task.py中有一个任务,如下所示:

@app.task
def location(request):
....

我试图将请求对象直接从几个传递给任务,如下所示:

def tag_location(request):
    tasks.location.delay(request)
    return JsonResponse({'response': 1})

我收到一个无法序列化的错误,我猜是吗?我该如何解决?麻烦的是我也有文件上传对象..它不是所有简单的数据类型。

关注者
0
被浏览
109
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    因为请求对象包含对不实际序列化的内容的引用(例如上载的文件或与请求关联的套接字),所以没有通用的方法来对其进行序列化。

    相反,您应该拔出并传递需要的部分。例如,类似:

    import tempfile
    
    @app.task
    def location(user_id, uploaded_file_path):
        # … do stuff …
    
    def tag_location(request):
        with tempfile.NamedTemporaryFile(delete=False) as f:
            for chunk in request.FILES["some_file"].chunks():
                f.write(chunk)
        tasks.location.delay(request.user.id, f.name)
        return JsonResponse({'response': 1})
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看