如何使用python请求进行多个api调用

时间:2019-07-05 23:10:59

标签: python django api python-requests sendasynchronousrequest

我正在尝试使用请求或允许我执行此操作的任何其他库从Django并行调用外部api。

我已经尝试使用grequests进行此调用,有时它可以工作,但是大多数情况下,我在客户端获取“ NoneType”对象没有属性“ json”错误。 这是我的密码

views.py

def get_fixtures(request, league_id):
league_id = league_id

urls = [
    "https://api-football-v1.p.rapidapi.com/v2/fixtures/league/%d" % league_id,
    "https://api-football-v1.p.rapidapi.com/v2/leagues/league/%d" % league_id
]
headers = {'X-RapidAPI-Host': "api-football-v1.p.rapidapi.com", 'X-RapidAPI-Key': X_RapidAPI_Key}
resp = (grequests.get(u, headers=headers) for u in urls)
responses = grequests.map(resp)
a = responses[0].json()
b = responses[1].json()
fix_1 = a['api']['fixtures']
api_2 = b['api']['leagues']

context = {

    'fix_1': fix_1,
    'api_2': api_2,
}

return render(request, "pages/fixtures.html", context)

在服务器端,我收到此错误:

File "src\gevent\_greenlet_primitives.py", line 60, in 
gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src\gevent\_greenlet_primitives.py", line 64, in 
gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch
File "src\gevent\__greenlet_primitives.pxd", line 35, in 
gevent.__greenlet_primitives._greenlet_switch
greenlet.error: cannot switch to a different thread.

我可以使用请求或任何其他库来执行调用而不会出现这些错误吗?如果是,我如何在工作中实施它?

2 个答案:

答案 0 :(得分:1)

导入 grequests

def call_with_grequests(urls,title_description):

# calling API's with grequests
responses = (grequests.post(u,json={"title_description":title_description}) for u in urls)
data=grequests.map(responses)
topiclassifier_result=data[0].json()
tagextraction_result=data[1].json()
return topiclassifier_result,tagextraction_result

答案 1 :(得分:0)

尝试放置:

resp = list(grequests.get(u, headers=headers) for u in urls)