I am trying to make parallel calls to external apis from django using requests or any other library that allows me to do this.
I have already tried using grequests to make this calls, sometimes it works but most times I get ‘NoneType’ object has no attribute ‘json’ error on the client side. Here are my codes
views.py
JavaScript
x
23
23
1
def get_fixtures(request, league_id):
2
league_id = league_id
3
4
urls = [
5
"https://api-football-v1.p.rapidapi.com/v2/fixtures/league/%d" % league_id,
6
"https://api-football-v1.p.rapidapi.com/v2/leagues/league/%d" % league_id
7
]
8
headers = {'X-RapidAPI-Host': "api-football-v1.p.rapidapi.com", 'X-RapidAPI-Key': X_RapidAPI_Key}
9
resp = (grequests.get(u, headers=headers) for u in urls)
10
responses = grequests.map(resp)
11
a = responses[0].json()
12
b = responses[1].json()
13
fix_1 = a['api']['fixtures']
14
api_2 = b['api']['leagues']
15
16
context = {
17
18
'fix_1': fix_1,
19
'api_2': api_2,
20
}
21
22
return render(request, "pages/fixtures.html", context)
23
On the server side i get this error:
JavaScript
1
8
1
File "srcgevent_greenlet_primitives.py", line 60, in
2
gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
3
File "srcgevent_greenlet_primitives.py", line 64, in
4
gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
5
File "srcgevent__greenlet_primitives.pxd", line 35, in
6
gevent.__greenlet_primitives._greenlet_switch
7
greenlet.error: cannot switch to a different thread.
8
Can I use requests or any other library to perform the calls without getting these errors? if yes how do i implement it in my work?
Advertisement
Answer
Try placing this:
JavaScript
1
2
1
resp = list(grequests.get(u, headers=headers) for u in urls)
2