我有一個大約 70 個專案的串列,我需要為每個專案發出一個 api 請求。我目前正在使用 for 回圈遍歷該串列中的每個專案并發出 api 請求。有沒有更有效的方法來做到這一點?我想有一種方法可以同時發出 api 請求而不是回圈。
uj5u.com熱心網友回復:
如果可能,您應該使用某種并行性,例如Pool類。
uj5u.com熱心網友回復:
我會用httpx
async def send_request(item):
async with httpx.AsyncClient() as client:
r = await client.get('https://www.example.com/', data=item)
return r.json()
async def main():
data = [{"hi": 1}, {"hi": 2}]
coros = [send_request(x) for x in data]
results = await asyncio.gather(*coros)
return results
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
uj5u.com熱心網友回復:
您可以使用標準 python 庫threading:
def name_func(param):
do something
thread1=threading.Thread(target=name_func, args =(a,))
thread2=threading.Thread(target=name_func, args =(b,))
thread1.start()
thread2.start()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/515394.html
標籤:Pythonapi循环
