Passing django request object to celery task

I have a task in tasks.py like:

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

      

I am trying to pass a request object from multiple to a task like this:

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

      

I am getting the error that it cannot be serialized I guess? How to fix it? the problem is i have files loading objects .. its not all simple data types.

+3


source to share


1 answer


Because the request object contains references to things that are impractical to serialize - like uploaded files or the socket associated with the request - there is no universal way to serialize it.

Instead, you should simply pull out and transfer the parts 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})

      

+2


source







All Articles