报错信息
使用 httpx 测试 fastapi 编写的接口并发性,抱以下错误:
发生异常: ReadTimeout
Cancelled by cancel scope 10e8024d0
asyncio.exceptions.CancelledError: Cancelled by cancel scope 10e8024d0
During handling of the above exception, another exception occurred:
TimeoutError:
During handling of the above exception, another exception occurred:
httpcore.ReadTimeout:
The above exception was the direct cause of the following exception:
File "/Users/xx/code/rqst_test/test.py", line 6, in fetch
response = await client.get(url)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/xx/code/rqst_test/test.py", line 13, in main
results = await asyncio.gather(*tasks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/xx/code/rqst_test/test.py", line 17, in <module>
asyncio.run(main())
httpx.ReadTimeout:
原因 response = await client.get(url)
没设置 timeout,设置完就可以了
请求
import httpx
import asyncio
async def fetch(client, url):
response = await client.get(url, timeout=60)
return response.status_code
async def main():
url = 'http://100.168.1.246:8003/long_task'
async with httpx.AsyncClient() as client:
tasks = [fetch(client, url) for _ in range(100)] # 并发100个请求
results = await asyncio.gather(*tasks)
print(results)
if __name__ == "__main__":
asyncio.run(main())
FastAPI 接口代码
如下:
import json
import asyncio
from fastapi import FastAPI
from fastapi.responses import JSONResponse
sum = 0
app = FastAPI()
@app.get("/")
def read_main():
return {"message": "Hello !"}
@app.get("/long_task")
async def long_task():
global sum
sum += 1
print('---- long-task ', sum )
await asyncio.sleep(10)
print('---- completed ', sum )
return {"message": f"Task {sum} completed"}
import os
PORT = 8003
if __name__ == '__main__':
import uvicorn
script = f'lsof -t -i tcp:{PORT} | xargs kill -9'
os.system(script)
uvicorn.run(app, host='0.0.0.0', port=PORT)