报错 - httpx - ReadTimeout Cancelled by cancel scope 10e8024d0

报错信息

使用 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)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值