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)
相关推荐
取个名字真难呐18 分钟前
相对位置2d矩阵和kron运算的思考
人工智能·pytorch·python·深度学习·线性代数·矩阵
珈百列34 分钟前
如何在jupyter notebook中使用django框架
ide·python·jupyter
旧厂街小江1 小时前
LeetCode第93题:复原IP地址
c++·python·算法
憨憨睡不醒啊1 小时前
自从有了Trae,让我实现从 conda 到 uv 的 Python 包管理自由😋😋😋
python·llm·trae
自由鬼1 小时前
企业在本地部署 Hugging Face后如何微调
人工智能·python·深度学习
没逻辑1 小时前
深入 Python 性能分析:工具与实战指南
后端·python
带娃的IT创业者1 小时前
《Python实战进阶》第32集:使用 TensorFlow 构建神经网络
python·神经网络·tensorflow
CodeCraft Studio2 小时前
Excel处理控件Aspose.Cells指南:如何在不使用 Microsoft Excel 的情况下解锁 Excel 工作表
python·microsoft·excel
这里有鱼汤2 小时前
一篇文章搞定Python数据分析用到的所有库
后端·python·程序员
这里有鱼汤2 小时前
Python自动化办公宝典,一篇文章搞定文档处理:PDF、Word、Excel文档全攻略
后端·python·程序员