python - 如何使用 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.
我可以使用请求或任何其他库来执行调用而不会出现这些错误吗?如果是,我如何在我的工作中实现它?
解决方案
尝试放置这个:
resp = list(grequests.get(u, headers=headers) for u in urls)
推荐阅读
- angular - 在 Angular 中使用 mat-form-field 时启动画面挂起
- r - 如何将键值和图例放在热图的底部
- cassandra - 从 Cassandra 中的多 DC 集群中删除 DC
- javascript - 开玩笑模拟 readFile,writeFile 不加载我的模拟
- c# - 如何从 C# 中的组合框获取第一项?
- java - Spring Boot Gradle Java 应用程序中的 SQL Server 依赖项
- c - 如何从线程返回值返回到 main()
- python - 通过 Anaconda 使用 Visual Studio 的问题
- vue.js - 在没有点击事件Vue js的情况下在子组件之间传递“ref”
- kubernetes - 使用 Google Cloud 的 Web 应用程序部署方法 - GKE