【问题标题】:FastAPI RuntimeError: Use params or add_paginationFastAPI RuntimeError: Use params or add_pagination
【发布时间】:2022-12-27 16:02:29
【问题描述】:

I'm writing my second project on FastAPI. And I got this error. For example I have this code in my routers.users.py:

@router.get('/', response_model=Page[Users])
async def get_all_users(db: Session = Depends(get_db)):
    return paginate(db.query(models.User).order_by(models.User.id))

And it works. It has fields limit and page in swagger documentation. I tried to write the same for routers.recipes.py, but in this case I have no fields for pagination(limit, page) in swagger. Ok, I googled and found out that adding dependencies could help me. And now I see pagination parameters in swagger, but error is still the same.

routers.recipes:

@router.get('/', response_model=Page[PostRecipes], dependencies=[Depends(Params)])
async def get_all_recipes(db: Session = Depends(get_db)):
    return paginate(db.query(models.Recipe).order_by(models.Recipe.id))

pagination:

class Params(BaseModel, AbstractParams):
    page: int = Query(1, ge=1, description="Page number")
    limit: int = Query(50, ge=1, le=100, description="Page size")

    def to_raw_params(self) -> RawParams:
        return RawParams(
            limit=self.limit,
            offset=self.limit * (self.page - 1),
        )


class Page(BasePage[T], Generic[T]):
    page: conint(ge=1)  # type: ignore
    limit: conint(ge=1)  # type: ignore

    __params_type__ = Params

    @classmethod
    def create(
        cls,
        items: Sequence[T],
        total: int,
        params: AbstractParams,
    ) -> Page[T]:
        if not isinstance(params, Params):
            raise ValueError("Page should be used with Params")

        return cls(
            total=total,
            items=items,
            page=params.page,
            limit=params.limit,
        )


__all__ = [
    "Params",
    "Page",
]

So, does anyone have ideas about it?

【问题讨论】:

    标签: fastapi


    【解决方案1】:

    according to doc you have to specify default parameters, your code should look like paginate(iterable, params)

    【讨论】:

      猜你喜欢
      • 2022-10-06
      • 2015-10-19
      • 2023-02-14
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-27
      相关资源
      最近更新 更多