python encoding_error ai_generated true

UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 的字节 0x80:无效的起始字节

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

ID: python/fastapi-unicodedecodeerror-request-body

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-10-15首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

请求体包含非 UTF-8 编码的数据,例如二进制或 Latin-1。

English

Request body contains non-UTF-8 encoded data, such as binary or Latin-1.

generic

解决方案

  1. 85% 成功率 Specify encoding when reading request body
    data = await request.body()
    text = data.decode('latin-1')  # or 'utf-8' with errors='replace'
  2. 90% 成功率 Use FastAPI's bytes type for raw data
    from fastapi import UploadFile
    @app.post('/upload')
    async def upload(file: UploadFile):
        content = await file.read()
        # handle bytes as needed

无效尝试

常见但无效的做法:

  1. Setting app default encoding to latin-1 globally 70% 失败

    Breaks other parts expecting UTF-8.

  2. Ignoring errors with errors='ignore' 60% 失败

    Data loss can occur.