CRUD operation with FastAPI and sqlalchemy

  Kiến thức lập trình

I’m new to python and fastapi and i’m to create a simple CRUD to create a user and if the user gets created correctly, create a blank profile with the user_id of the created user.

These are my Profile and User models:

class User(Base):
    __tablename__ = 'users'
    id = Column("id", Integer, primary_key=True, autoincrement=True)
    email = Column("email", String, unique=True, index=True)
    password = Column("password", String)
    created_at = Column("created_at", DateTime, default=func.now())

class Profile(Base):
    __tablename__ = 'profiles'
    id = Column("id", Integer, primary_key=True, autoincrement=True)
    user_id = Column("user_id", Integer, ForeignKey("users.id"))
    first_name = Column("first_name", String, nullable=True)
    last_name = Column("last_name", String, nullable=True)
    bio = Column("bio", String, nullable=True)
    created_at = Column("created_at", DateTime, default=func.now())

I also have some defined schemas:

class UserBase(BaseModel):
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int
    created_at: datetime

    class Config:
        from_attributes = True
    

class Profile(BaseModel):
    user_id: int
    first_name: Optional[str]
    last_name: Optional[str]
    bio: Optional[str]

    class Config:
        from_attributes = True

This is the endpoints file from where i’m calling the crud operations:

@router.post("/register", response_model=schemas.User)
async def register(usert: schemas.UserCreate, db: AsyncSession = Depends(get_db)):
    try:
        new_user = await user.create_user(db, usert)
        if(new_user):
            await profile.create_profile(db, new_user.id)
    except CustomException as e:
        raise HTTPException(status_code=e.status_code, detail=e.message)
    except Exception as e:
        raise HTTPException(status_code=400, detail=e)

    return new_user

And these are the crud operations create_user and create_profile

async def create_user(db: AsyncSession, user: UserCreate):
    db_user = await get_user_by_email(db, user.email)
    if(db_user):
        raise EmailAlreadyRegisteredError()
    hashed_password = hash_password(user.password)
    new_user = User(email=user.email, password=hashed_password)
    db.add(new_user)
    try:
        await db.commit()
        await db.refresh(new_user)
        return new_user
    except Exception:
        await db.rollback()
        raise CreatingUserError()

async def create_profile(db: AsyncSession, user_id: int):
    new_profile = Profile(user_id=user_id)
    db.add(new_profile)
    try:
        await db.commit()
        await db.refresh(new_profile)
        return new_profile
    except Exception:
        await db.rollback()
        raise CreatingProfileError()

I get this error when I submit a the post request:

fastapi.exceptions.ResponseValidationError: 3 validation errors:
  {'type': 'get_attribute_error', 'loc': ('response', 'email'), 'msg': "Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)", 'input': <app.db.models.User object at 0x104e160f0>, 'ctx': {'error': "MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)"}}
  {'type': 'get_attribute_error', 'loc': ('response', 'id'), 'msg': "Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)", 'input': <app.db.models.User object at 0x104e160f0>, 'ctx': {'error': "MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)"}}
  {'type': 'get_attribute_error', 'loc': ('response', 'created_at'), 'msg': "Error extracting attribute: MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)", 'input': <app.db.models.User object at 0x104e160f0>, 'ctx': {'error': "MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s)"}}

And when I remove the response_model from the endpoint method I don’t get the error but i get an empty response.

BTW, the user and the profile are being created.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT