参考:https://cuiqingcai.com/6160.html
https://blog.csdn.net/cqcre/article/details/106132125
async是python自带的异步库
1、async结合httpx
import httpx
import asyncio
async def main():
async with httpx.AsyncClient() as client:
resp = await client.post('http://122.51.39.219:8000/query',
json={'ts': '2020-01-20 13:14:15'})
result = resp.json()
print(result)
asyncio.run(main())
发送100次请求
import httpx
import random
import datetime
import asyncio
import time
async def request(client, body):
resp = await client.post('http://122.51.39.219:8000/query', json=body)
result = resp.json()
print(result)
async def main():
async with httpx.AsyncClient() as client:
start = time.time()
task_list = []
for _ in range(100):
now = datetime.datetime.now()
delta = random.randint(5, 15)
ts = (now - datetime.timedelta(days=delta)).strftime('%Y-%m-%d %H:%M:%S')
req = request(client, {'ts': ts})
task = asyncio.create_task(req)
task_list.append(task)
await asyncio.gather(*task_list)
end = time.time()
print(f'发送100次请求,耗时:{end - start}')
asyncio.run(main())
2、async结合aiohttp
import aiohttp
import asyncio
async def main():
async with aiohttp.ClientSession() as client:
resp = await client.post('http://122.51.39.219:8000/query',
json={'ts': '2020-01-20 13:14:15'})
result = await resp.json()
print(result)
asyncio.run(main())
发送100次请求
import aiohttp
import random
import datetime
import asyncio
import time
async def request(client, body):
resp = await client.post('http://122.51.39.219:8000/query', json=body)
result = await resp.json()
print(result)
async def main():
async with aiohttp.ClientSession() as client:
start = time.time()
task_list = []
for _ in range(100):
now = datetime.datetime.now()
delta = random.randint(5, 15)
ts = (now - datetime.timedelta(days=delta)).strftime('%Y-%m-%d %H:%M:%S')
req = request(client, {'ts': ts})
task = asyncio.create_task(req)
task_list.append(task)
await asyncio.gather(*task_list)
end = time.time()
print(f'发送100次请求,耗时:{end - start}')
asyncio.run(main())