1

Is there a way to pass request object from one view to another? Or do I have to dissect the request into individual parts or use request.__dict__ and pass those?

Currenlty, because the request cannot be serialized, the below code:

def explorer(request):
    collect_activities_init(request)
    return render(request, 'explorer/explorer.html')

def collect_activities_init(request):
    task = collect_activities.delay(request)
    return JsonResponse({'status_url': reverse('explorer:collect_activities_status', kwargs={'task_id': task.id})})

@celery.task(bind=True)
def collect_activities(self, request):
    api = StravaApi()
    code = request.GET.get('code', '') # extract code from redirect URL query string

Will give:

WSGIRequest: GET '/explorer/?state=&code=3ba4hgh5ad99ea3cf8e52d8&scope='> is not JSON serializable

But I need to have the request data from the first function in the last one, because its code extracts some data from the request.

barciewicz
  • 3,511
  • 6
  • 32
  • 72

2 Answers2

1

I found this: Django pass object from view to next for processing

The top answer uses sessions in order to pass the save the object and retrieve it later:

def first_view(request):
    my_thing = {'foo' : 'bar'}
    request.session['my_thing'] = my_thing
    return render(request, 'some_template.html')

def second_view(request):
    my_thing = request.session.get('my_thing', None)
    return render(request, 'some_other_template.html', {'my_thing' : my_thing})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Caleb Lawrence
  • 131
  • 1
  • 4
  • 11
1

The problem you're having is not passing request between those functions, but rather that celery requires arguments passed to a celery task to be serialized.

The simple solution here would be to pull out the attributes you need from the request then pass those to the task.

So instead of

task = collect_activities.delay(request)

Do

code = request.GET.get('code', '')
task = collect_activities.delay(code)

Of course, you'll need to change the collect_activities task definition to accept the code as an argument, rather than a request object.

sytech
  • 29,298
  • 3
  • 45
  • 86