【问题标题】:How to make multiple api calls with python requests如何使用 python 请求进行多个 api 调用
【发布时间】:2019-11-16 12:00:02
【问题描述】:

我正在尝试使用 requests 或任何其他允许我执行此操作的库从 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.

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

【问题讨论】:

    标签: python django api python-requests sendasynchronousrequest


    【解决方案1】:

    尝试放置这个:

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

    【讨论】:

    • 这很有帮助。它似乎工作得更好。但我仍然得到:文件“src\gevent__greenlet_primitives.pxd”,第 35 行,在 gevent.__greenlet_primitives._greenlet_switch greenlet.error: cannot switch to a different thread。在我的本地服务器上
    • @Bruce 你解决过这个问题吗?我也有同样的问题
    猜你喜欢
    • 2019-03-31
    • 2017-11-14
    • 2020-12-31
    • 2020-05-11
    • 1970-01-01
    • 2013-07-11
    • 2018-06-04
    • 1970-01-01
    • 2016-04-20
    相关资源
    最近更新 更多