首页 > 解决方案 > 如何使用 python 请求进行多个 api 调用

问题描述

我正在尝试使用 requests 或任何其他允许我执行此操作的库从 django 对外部 API 进行并行调用。

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

视图.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.

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

标签: pythondjangoapipython-requestssendasynchronousrequest

解决方案


尝试放置这个:

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

推荐阅读