aiohttp调用compile.ndjson接口触发未读取响应体编码识别错误
错误触发原因
- 你封装的
_post方法存在逻辑顺序错误:拿到响应对象后,在未触发任何响应体读取操作的前提下,就提前调用了response.get_encoding()。 - aiohttp的
get_encoding()方法有明确前置约束:如果响应头的Content-Type字段没有显式标注charset=xxx,必须先读取/缓存响应体内容,才能通过内容探测推断编码。 - 其余普通接口的响应头均自带明确的charset参数,因此提前调用
get_encoding()不会触发问题;仅/compile.ndjson接口返回的Content-Type无charset声明,才会抛出当前的RuntimeError。 - 你手动给
response.json()传入content_type和encoding参数完全冗余,aiohttp的内置json方法已经自动实现了编码探测、响应体读取的全流程逻辑。
修复方案
分两步处理:先解决编码报错问题,再适配NDJSON格式的正确解析逻辑。
1. 修正通用_post方法逻辑
移除手动获取encoding、手动传参的冗余逻辑,让aiohttp自动处理编码探测;同时新增可选参数支持返回原始文本,适配NDJSON类接口的解析需求:
@classmethod async def _post(cls, url, *args, return_raw: bool = False, **kwargs): async with cls.session.post(*args, url=url, ssl=False, **kwargs) as response: response.raise_for_status() if return_raw: # response.text()会自动触发响应体读取,aiohttp自动完成编码探测 return await response.text() # 普通JSON接口直接走内置解析逻辑 return await response.json()
2. 适配compile_nd的NDJSON响应解析
NDJSON格式为“每行一个独立JSON对象”,无法直接用response.json()解析,需要手动拆分逐行解析:
@classmethod async def compile_nd( cls, code: str, compiler: str, codes: typing.List[dict] = (), compiler_option_raw: typing.Any = '', options: str = '', runtime_option_raw: typing.Any = '', stdin: str = '', **kwargs ): params = { 'code': code, 'codes': codes, 'compiler': compiler, 'compiler-option-raw': compiler_option_raw, 'options': options, 'runtime-option-raw': runtime_option_raw, 'stdin': stdin } headers = {'Content-type': 'application/x-ndjson', 'Accept': 'text/plain'} # 调用_post时指定return_raw=True,获取未拆分的原始响应文本 raw_resp = await cls._post( url=cls.url.format("compile.ndjson"), data=json.dumps(params), headers=headers, return_raw=True, **kwargs ) # 逐行解析NDJSON,合并为最终返回的字典(可根据实际接口返回调整合并规则) result = {} for line in raw_resp.splitlines(): stripped_line = line.strip() if not stripped_line: continue line_json = json.loads(stripped_line) result.update(line_json) return result
额外注意点
- 原来
_post里手动传content_type=response.content_type给response.json()还会触发另一个潜在问题:aiohttp默认会校验响应的Content-Type是否为JSON格式,如果NDJSON接口返回的Content-Type不是标准application/json,会直接抛ContentTypeError。改用上面的适配逻辑后,这个问题也会一并解决。 - 可以核对下接口文档的请求头要求:当前你传入的是
application/x-ndjson,但请求体是单个JSON序列化后的字符串,如果接口要求请求体为标准JSON,需要把请求头改成Content-Type: application/json。
内容的提问来源于stack exchange,提问作者Táwros
相关产品推荐
相关产品推荐

