FastAPI Python的PUT请求

huangapple go评论58阅读模式
英文:

FastAPI python PUT request

问题

试图运行 put 请求时,我一直收到错误消息,指示对象类型 'User' 没有 'first_name' 属性,尽管我在模式中声明了 'first_name'。这是我的 API 请求代码,调用了 services 中的 update_user 函数。

@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"}

服务部分:

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)

模式部分:

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

模型部分:

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();
    }
  };

在运行请求时,我收到错误消息 AttributeError: type object 'User' has no attribute 'first_name'

英文:

im trying to run a put request but i keep getting error type object 'User' has no attribute 'first_name' when i have declared first_name in the schema. this is my code for the api request which calls the function update_user from services.

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)

request from frontend:

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();
    }
  };

when running the request i get the error

AttributeError: type object 'User' has no attribute 'first_name'

答案1

得分: 3

错误消息中暗示的问题是在这句话中:“AttributeError: type object 'User' has no attribute 'first_name'”。这意味着在某个地方,你正在将一个变量赋值给User类型,而不是User类的实例。

我认为发生这种情况的地方是在主文件中,你有user = _schemas.User。这会将user 的默认值设置为 _schemas.User 类型。我认为你试图对user 进行类型提示,表示user 将是 _shcmas.User 类型。如果是这样,你应该使用冒号而不是等号,像这样:user: _schemas.User。你还设置了id = int 而不是 id: int。在你修复这两个类型提示错误后,一切都应该正常工作。

英文:

What is wrong is hinted at in the error message. If you read it carefully, it says "AttributeError: type object 'User' has no attribute 'first_name'". This means somewhere, you're assigning a variable into the type of User instead of an instance of the User class.

And I believe the place where that happened is in the main file where you had user = _schemas.User. This sets the default value of user to be the type of _schemas.User. I believe you are trying to type hint that user is going to be of type _shcmas.User. If that's the case you should use colon instead of equals like so: user: _schemas.User. You also set id = int instead of id: int. Everything should work after you fix those two type hint mishaps.

@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"}

huangapple
  • 本文由 发表于 2023年4月4日 07:21:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定