You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI容器重启后Get路由报错,其余路由运行正常

解决Docker重启后FastAPI Get路由的字典更新与vars()报错

错误原因拆解

  • ValueError('dictionary update sequence element #0 has length 3; 2 is required'):代码里存在用长度不为2的序列(比如三元组)更新字典,或是jsonable_encoder处理后的返回结构不符合键值对要求。
  • TypeError('vars() argument must have dict attribute'):vars()被传入了没有__dict__属性的对象——比如内置类型(str、int)、元组、列表,或是没正确实现属性访问的类。

排查修复步骤

1. 检查jsonable_encoder与vars()的搭配使用

如果你的路由里用了jsonable_encoder(vars(some_object)),先确认some_object类型:

  • 要是SQLAlchemy模型,别用vars(),给模型对应的Pydantic类加上orm_mode = True,直接返回模型实例即可,FastAPI会自动序列化。
  • 要是自定义类,要么确保类有__dict__属性,要么改用dataclasses.asdict()(如果是dataclass)替代vars()。
  • 绝对别给内置类型(比如字符串、数字)用vars(),这本身就会触发TypeError。

2. 排查字典更新逻辑

找路由里所有dict.update()或者用序列构造字典的代码(比如dict(some_sequence))。比如写了data.update([("a", "b", "c")])这种三元组序列,肯定会炸——必须保证每个序列元素都是长度为2的键值对(比如(key, value))。

3. 验证Docker重启后的配置/数据

容器重启后,服务加载的配置文件、初始化数据可能和之前不一样。比如配置文件JSON格式错误,解析出的是畸形结构,也会引发这类报错。进容器里直接查看配置文件内容,确认格式正确,没有多余的元素或缺失的键值对。

示例修复代码

错误写法(触发报错):

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder

app = FastAPI()

class Item:
    def __init__(self, name: str, price: float):
        self.name = name
        self.price = price

@app.get("/item")
async def get_item():
    item = Item("test", 10.0)
    # 若item是无__dict__的对象,vars()直接报错
    return JSONResponse(content=jsonable_encoder(vars(item)))

修复写法(用Pydantic模型更稳妥):

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/item", response_model=Item)
async def get_item():
    # 直接返回字典或数据库模型实例,response_model自动处理序列化
    return {"name": "test", "price": 10.0}

如果必须用jsonable_encoder,替换vars():

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from dataclasses import dataclass, asdict

app = FastAPI()

@dataclass
class Item:
    name: str
    price: float

@app.get("/item")
async def get_item():
    item = Item("test", 10.0)
    # 用asdict替代vars(),避免属性访问问题
    return JSONResponse(content=jsonable_encoder(asdict(item)))

内容的提问来源于stack exchange,提问作者M.K.S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:22:38