httpx.AsyncClient()的stream方法设置timeout超时

目录

问题描述

使用httpx的异步请求AsyncClient调用stream方法请求流式接口,如果接口返回内容比较慢(比如第一个字符返回用时5s),客户端主动关闭流式通道,导致当后端接口准备好数据后,返回报错"管道已关闭"

解决办法

调用stream方法增加参数timeout

复制代码
    async def get_answer(self, job, index, text, callback):
        async with httpx.AsyncClient() as c:
            try:
                url = "流式接口地址api" 
                headers = {
                    'Authorization': g.TOKEN,
                    'Clientid': g.CLIENT_SIGN,
                    "Accept": "*/*",
                    "Cache-Control": "no-store"
                }
                params = {
                    "question": text
                }
                # 重点 增加超时配置
                timeout_config = Timeout(5.0, read=10.0)  # 总超时设为5秒,但读取超时设为10秒
                async with c.stream('GET', url, headers=headers, params=params, timeout=timeout_config) as response:
                    content_type = response.headers.get('content-type', '').lower()
                    if 'text/event-stream' in content_type:     # 流式回答
                        all_answer = ""
                        async for data in EventSource(response).aiter_sse():
                            if data:
                                all_answer += data.data
               # 省略代码
            except Exception as e:
                print(e)
相关推荐
2601_962381589 小时前
ArcGIS+Python+AI赋能高标准农田建设项目审计提质增效
python·arcgis·ai·高标准农田审计·大数据审计
rust&python9 小时前
课程表的归一化处理
python·程序人生·信息可视化
2601_9620990810 小时前
replit如何运行python
python·代码编辑器·编程环境·在线ide·replit
头发够用的程序员10 小时前
别被 TOPS 参数迷惑:手把手推导边缘 GPU 整型算力
人工智能·python·ubuntu·计算机视觉·硬件架构·边缘计算
TechWayfarer10 小时前
做IP归属地查询时总是查不准?IP纯净度检测实战:从“查归属地“到识别“脏IP“的四个维度
服务器·网络·python·tcp/ip·安全·web安全
小溪学编程11 小时前
Java InputStream 详解:从基础到实战
java·python·php
笨笨饿11 小时前
#137_死机恢复现场_Armino平台AP系统swd调试
git·python·stm32·单片机·嵌入式硬件·物联网·vim
2601_9623824311 小时前
python常用函数大全pdf-python函数大全.pdf
python·内置函数·io操作·集合操作·数学运算
奈斯先生Vector12 小时前
AIGC 视频生成实战:用 Kling Video 拆解文生视频、图生视频与完整工作流
开发语言·人工智能·windows·python·aigc·音视频
小玮看世界12 小时前
[Python]螺旋遍历 vs 最短路径:方向控制类算法的“同源异流”
开发语言·python·算法