我需要在不同的服务器上不断向大约 150 个 API 发出许多请求。我跟交易工作,时间很关键,我不能浪费1毫秒。
我发现的解决方案和问题是:
也许是使用所有这些的解决方案。
如果 Python 中没有真正好的解决方案,我应该用什么来代替?
# Using Asyncio
import asyncio
import requests
async def main():
loop = asyncio.get_event_loop()
future1 = loop.run_in_executor(None, requests.get, 'http://www.google.com')
future2 = loop.run_in_executor(None, requests.get, 'http://www.google.co.uk')
response1 = await future1
response2 = await future2
print(response1.text)
print(response2.text)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Using Threads
from threading import Thread
def do_api(url):
#...
#...
#...
#...
for i in range(50):
t = Thread(target=do_apis, args=(url_api[i],))
t.start()
Run Code Online (Sandbox Code Playgroud)