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

FastAPI PUT请求报错:type object 'User'无first_name属性求助

问题:FastAPI PUT请求更新用户信息时触发AttributeError: type object 'User' has no attribute 'first_name'

运行FastAPI的PUT请求更新用户信息时,尽管已在Schema中声明first_name字段,却持续触发错误:AttributeError: type object 'User' has no attribute 'first_name'。相关代码如下:

相关代码

main.py

@app.put("/api/userUpdate/{id}", status_code=200)
async def update_User(
    id = int,
    user = _schemas.User,
    db: _orm.Session = _fastapi.Depends(_services.get_db),
):
    await _services.update_user(id, user, db)
    return {"message", "Successfully Updated"}

services.py

async def get_user_by_id(id: int, db: _orm.Session):
    return db.query(_models.User).filter(_models.User.id == id).first()

async def update_user(id: int, user: _schemas.User, db: _orm.Session):
    user_db = await get_user_by_id(id, db)

    user_db.first_name = user.first_name
    user_db.last_name = user.last_name
    user_db.email = user.email

    db.commit()
    db.refresh(user_db)

    return _schemas.User.from_orm(user_db)

schemas.py

class _UserBase(_pydantic.BaseModel):
    email: str
    
    
class UserCreate(_UserBase):
    hashed_password: str
    first_name: str
    last_name: str
    user_role : str
    
    class Config:
        orm_mode = True


class User(_UserBase):
    id: int
    first_name: str
    last_name: str
    user_role : str

    class Config:
        orm_mode = True

models.py

class User(_database.Base):
    __tablename__ = "users"
    id = _sql.Column(_sql.Integer, primary_key=True, index=True)
    email = _sql.Column(_sql.String, unique=True, index=True)
    hashed_password = _sql.Column(_sql.String)
    first_name = _sql.Column(_sql.String, index=True)
    last_name = _sql.Column(_sql.String, index=True)
    user_role = _sql.Column(_sql.String, index = True)
    
    leads = _orm.relationship("Lead", back_populates="owner")

    def verify_password(self, password: str):
        return _hash.bcrypt.verify(password, self.hashed_password)

前端请求代码

const handleUpdateUser = async (e) => {
    e.preventDefault();
    const requestOptions = {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + token,
      },
      body: JSON.stringify({
        first_name: userName,
        last_name: userSurname,
        email: userEmail,
      }),
    };
    const response = await fetch(`/api/userUpdate/${id}`, requestOptions);
    if (!response.ok) {
      setErrorMessage("Something went wrong when updating lead");
    } else {
      cleanFormData();
      handleModal();
    }
  };

错误原因

错误核心出在main.py的路由参数定义:

  • 代码中id = int和user = _schemas.User的写法不符合FastAPI规范,这会直接把id赋值为int类型对象、user赋值为_schemas.User类对象,而非FastAPI自动解析后的请求参数/请求体实例。
  • 当services.py中尝试访问user.first_name时,实际是在访问_schemas.User类的静态属性,而非实例属性,因此触发AttributeError。

修复方案

1. 修正路由参数定义

使用类型注解声明参数类型,这是FastAPI解析请求参数和请求体的标准方式:

@app.put("/api/userUpdate/{id}", status_code=200)
async def update_User(
    id: int,  # 类型注解声明路径参数
    user: _schemas.User,  # 类型注解声明请求体
    db: _orm.Session = _fastapi.Depends(_services.get_db),
):
    await _services.update_user(id, user, db)
    return {"message": "Successfully Updated"}

同时注意:原返回语句用了集合语法{"message", "Successfully Updated"},需改为字典语法{"message": "Successfully Updated"},否则会返回格式错误。

2. 补充用户存在性校验

避免数据库中无对应ID用户时触发新错误,在services.py中添加判断:

async def update_user(id: int, user: _schemas.User, db: _orm.Session):
    user_db = await get_user_by_id(id, db)
    if not user_db:
        raise _fastapi.HTTPException(status_code=404, detail="User not found")
    
    user_db.first_name = user.first_name
    user_db.last_name = user.last_name
    user_db.email = user.email

    db.commit()
    db.refresh(user_db)

    return _schemas.User.from_orm(user_db)

3. 修正前端提示文案

前端错误提示中的"Something went wrong when updating lead"与更新用户的场景不符,建议改为:

setErrorMessage("Something went wrong when updating user");

内容的提问来源于stack exchange,提问作者user15299152

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:05:40