将Django请求对象传递给芹菜任务 [英] passing django request object to celery task

查看:63
本文介绍了将Django请求对象传递给芹菜任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在task.py中有一个任务,像这样:

I have a task in tasks.py like so:

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

我正在尝试直接从a传递请求对象很少有像这样的任务:

I am trying to pass the request object directly from a few to task like so:

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

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

I am getting an error that it can't be serialized i guess? How do I fix this? trouble is I have file upload objects as well .. its not all simple data types.

推荐答案

因为请求对象包含对序列化不实际的事情(例如上载的文件或与请求关联的套接字)没有通用的序列化方法。

Because the request object contains references to things which aren't practical to serialize — like uploaded files, or the socket associated with the request — there's no general purpose way to serialize it.

相反,您应该拉出并传递您需要的部分。例如,

Instead, you should just pull out and pass the portions of it that you need. For example, something like:

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})

这篇关于将Django请求对象传递给芹菜任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆