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)
相关推荐
Dxy123931021621 小时前
python把文件从一个文件复制到另一个文件夹
开发语言·python
sonrisa_1 天前
collections模块
python
折翼的恶魔1 天前
数据分析:排序
python·数据分析·pandas
天雪浪子1 天前
Python入门教程之赋值运算符
开发语言·python
站大爷IP1 天前
5个技巧写出专业Python代码:从新手到进阶的实用指南
python
hrrrrb1 天前
【Python】字符串
java·前端·python
大翻哥哥1 天前
Python 2025:低代码开发与自动化运维的新纪元
运维·python·低代码
Source.Liu1 天前
【Pywinauto库】12.2 pywinauto.element_info 后端内部实施模块
windows·python·自动化
Source.Liu1 天前
【Pywinauto库】12.1 pywinauto.backend 后端内部实施模块
开发语言·windows·python·自动化
用户8356290780511 天前
用Python高效处理Excel数据:Excel数据读取指南
后端·python