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

时间:2015-07-08 21:25:46

标签: python django celery

我在tasks.py中有一个任务,如:

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

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

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

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

1 个答案:

答案 0 :(得分:7)

因为请求对象包含对序列化不实用的东西的引用 - 比如上传文件或与请求相关联的套接字 - 所以没有通用的方法来序列化它。

相反,你应该拔出并传递你需要的部分。例如,像:

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})
相关问题