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)
相关推荐
quikai19816 小时前
python练习第二组
开发语言·python
熊猫_豆豆6 小时前
python 用手势控制程序窗口文字大小
python·手势识别
测试秃头怪6 小时前
2026最新软件测试面试八股文(含答案+文档)
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
LUU_796 小时前
Day29 异常处理
python
子夜江寒7 小时前
Python 学习-Day8-执行其他应用程序
python·学习
背心2块钱包邮7 小时前
第7节——积分技巧(Integration Techniques)-代换积分法
人工智能·python·深度学习·matplotlib
一个散步者的梦7 小时前
一键生成数据分析报告:Python的ydata-profiling模块(汉化)
python·数据挖掘·数据分析
黑客思维者8 小时前
Python大规模数据处理OOM突围:从迭代器原理到TB级文件实战优化
开发语言·python·github·迭代器·oom
weixin_421133418 小时前
应用日志监控
python
CHANG_THE_WORLD9 小时前
Python 学习三 Python字符串拼接详解
开发语言·python·学习