簡體   English   中英

如何使用python請求進行多個api調用

[英]How to make multiple api calls with python requests

我正在嘗試使用請求或任何其他允許我執行此操作的庫從 django 對外部 apis 進行並行調用。

我已經嘗試使用 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.

我可以使用請求或任何其他庫來執行調用而不會出現這些錯誤嗎? 如果是,我如何在我的工作中實現它?

導入 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

嘗試放置此:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM