1

This is my function in views.py which calls the api and send the response on html page.

   r = requests.post(RUN_URL, data=data)
   return JsonResponse(r.json(), safe=False)

I have a global variable 'counter' which I want to return along with that r.json().

   return JsonResponse(r.json(),counter, safe=False)

When I tried this code it gives me a error:

  TypeError: 'int' object is not callable

1 Answers1

1

You can create a dictionary where you return both the data and the counter, like:

return JsonResponse({'data': r.json(), 'counter': counter})

I have a global variable 'counter'.

Please do not use global variables. Global variables introduce a global state, which makes testing, refactoring, and distributing software very painful.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Hey I tried implementing this but then I couldn't get output on the html page. And I'll keep that in mind about the global variables. Thanks – Viraj Gaonkar Apr 13 '21 at 14:07
  • @VirajGaonkar: if you make a request, and `data` is the response, you access the result with `data.data` and the counter with `data.counter`. – Willem Van Onsem Apr 13 '21 at 14:11
  • Is there any way where I can append the counter variable in the r.json() itself? – Viraj Gaonkar Apr 13 '21 at 15:38
  • @VirajGaonkar: yes, but what is `r.json()`. If it is a list, it makes no sense to do this. Especially since sending lists as JSON data is *unsafe*: see https://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/ – Willem Van Onsem Apr 13 '21 at 15:39