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)
相关推荐
JaydenAI3 分钟前
[对比学习LangChain和MAF-07]如何引入人机交互的审批流程
python·ai·langchain·c#·agent·hitl·maf
神奇元创40 分钟前
商用级光路加速卡:大模型推理的极速落地方案
python·神经网络·fpga开发·dsp开发
运筹vivo@1 小时前
Python ContextVar 底层机制与内存模型拆解
前端·数据库·python
大白菜和MySQL1 小时前
java应用排查高线程
java·python
嵌入式协会20240721 小时前
(已解决)MinIO python 获取预签名出现forbidden、errornetwork等错误
java·开发语言·python
宸丶一1 小时前
Day 14:任务追踪 - 让 Agent 拥有项目管理能力
开发语言·python
skylar02 小时前
小白1分钟安装flash-attn
开发语言·python
JustNow_Man2 小时前
psmux快捷键
人工智能·python
默子昂2 小时前
ollama 自定义ui
开发语言·python·ui