我计划在 python 3 中编写异步请求。我遇到了 2 个包 urlib 和 requests。我很困惑使用以下哪个包可以为我提供更高的性能并且不会消耗太多资源。
这可能对每个人来说都是一个观点,但相信我,事实并非如此:
如果你必须问,你永远不会知道,也就是说,只需使用aiohttp。
我知道这是一个非常古老的问题,您可能也已经得到了答案,但这是我的脚本,以防有人仍在寻找解决方案。
import asyncio
import aiohttp
import time
async def send_request(session, url, data, i):
start_time = time.time()
async with session.post(url, data=data) as response:
end_time = time.time()
if response.status == 200:
print(f"Request {i+1} successful! Execution time: {end_time - start_time} seconds")
else:
print(f"Request {i+1} failed with status code: {response.status}")
async def send_multiple_requests(url, n):
data = {
'key1': 'value1' #replace with your actual request body
}
total_start_time = time.time()
async with aiohttp.ClientSession() as session:
tasks = []
for i in range(n):
task = asyncio.create_task(send_request(session, url, data, i))
tasks.append(task)
await asyncio.gather(*tasks)
total_end_time = time.time()
print(f"Total time to run {n} requests: {total_end_time - total_start_time} seconds\n")
url = 'https://example.com/abc' # Replace with your actual URL
n = 4 # Number of async requests
asyncio.run(send_multiple_requests(url, n))