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)
相关推荐
nvd111 小时前
Python 迭代器 (Iterator) vs. 生成器 (Generator)
开发语言·python
老罗-Mason1 小时前
Apache Flink运行环境搭建
python·flink·apache
Blossom.1182 小时前
大模型量化压缩实战:从FP16到INT4的生产级精度保持之路
开发语言·人工智能·python·深度学习·神经网络·目标检测·机器学习
linuxxx1102 小时前
Django 缓存详解与应用方法
python·缓存·django
野生工程师2 小时前
【Python爬虫基础-3】数据解析
开发语言·爬虫·python
道19932 小时前
python实现电脑手势识别截图
开发语言·python
shixian10304113 小时前
conda安装Django+pg运行环境
python·django·conda
jiaoxingk3 小时前
Django 接口文档生成:Swagger 与 ReDoc 全面说明
python·django
CodeCraft Studio3 小时前
国产化Excel开发组件Spire.XLS教程:Python将列表导出为CSV文件(含一维/二维/字典列表)
开发语言·python·excel·csv·spire.xls·列表导出为csv