full-stack-fastapi-template
full-stack-fastapi-template copied to clipboard
CRUD update pattern is broken with fastapi 0.61
The first line of the CRUDBase update method is:
obj_data = jsonable_encoder(db_obj)
This now stack overflows when using fastapi 0.61. We need an updated base CRUD pattern in this project, along with updating the various dependencies. I'll additionally be filing an issue to the fastapi project itself with the need for CRUD update examples.
From what I've figured out so far, we may need a reference to the ModelInDB or Model pydantic models, and then:
obj_data = ModelInDB.from_orm(db_obj)
and change the iteration to:
for field in obj_data.dict():
I fixed this issue by adding as_dict() to base_class.py in db:
@as_declarative()
class Base:
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
def as_dict(self) -> dict:
return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}
Then adding as_dict() to the db_obj in update in base.py in crud:
obj_data = jsonable_encoder(db_obj.as_dict())
Excuse me. Any examples? I found there is a bug about user update API. e.g.: in crud_user.py
def update(
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
) -> User:
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
# if update_data["password"]: # may cause a KeyError
if update_data.get("password", None): # changed
hashed_password = get_password_hash(update_data["password"])
del update_data["password"]
update_data["hashed_password"] = hashed_password
return super().update(db, db_obj=db_obj, obj_in=update_data)
Outdated