带字节的快速API JSON响应

2024-09-27 23:17:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个快速API来检索包含一些字节的mongo文档。结构如下

item = 
{"namd" : "xyz",
 "value1: b'\x89PNG\r\n\sla\..."
...
 "some_other_byte: b'\x89PNG\r\n\sla\..."  
}

使用FastAPI中的post请求返回上述数据,它尝试将其转换为json,但无法自动转换

所以我试了一下:

json_compatible_item_data = jsonable_encoder(item)

但是我得到了这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

有没有一种方法可以自动将上述dict转换为json,以便在restapi中返回?最好的方法是什么


Tags: 方法文档apijson字节mongosomebyte
1条回答
网友
1楼 · 发布于 2024-09-27 23:17:08

使用FastAPI jsonable_encoder可以使用自定义编码器。将任意bytes对象转换为base64str的示例:

json_compatible_item_data = jsonable_encoder(item, custom_encoder={
        bytes: lambda v: base64.b64encode(v).decode('utf-8')})

在客户端对目标字段进行解码可以如下所示:

value1 = base64.b64decode(response_dict["value1"])

相关问题 更多 >

    热门问题