Skip to content

Commit

Permalink
fix: handle incorrect per_page in projects (#129)
Browse files Browse the repository at this point in the history
More robust handling of the `page` and `per_page` headers in the projects blueprint.

Fixes some failing schemathesis tests.
  • Loading branch information
leafty committed Feb 28, 2024
1 parent f970a4d commit 78e9e49
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
6 changes: 5 additions & 1 deletion components/renku_data_services/project/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ async def _get_all(request: Request, *, user: base_models.APIUser):
page = int(page_parameter)
except ValueError:
raise errors.ValidationError(message=f"Invalid value for parameter 'page': {page_parameter}")
per_page = int(args.get("per_page", default_number_of_elements_per_page))
per_page_parameter = args.get("per_page", default_number_of_elements_per_page)
try:
per_page = int(per_page_parameter)
except ValueError:
raise errors.ValidationError(message=f"Invalid value for parameter 'per_page': {per_page_parameter}")

projects, pagination = await self.project_repo.get_projects(user=user, page=page, per_page=per_page)
return json(
Expand Down
5 changes: 4 additions & 1 deletion components/renku_data_services/project/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ async def get_projects(
"""Get all projects from the database."""
if page < 1:
raise errors.ValidationError(message="Parameter 'page' must be a natural number")
offset = (page - 1) * per_page
if offset > 2**63 - 1:
raise errors.ValidationError(message="Parameter 'page' is too large")
if per_page < 1 or per_page > 100:
raise errors.ValidationError(message="Parameter 'per_page' must be between 1 and 100")

Expand All @@ -61,7 +64,7 @@ async def get_projects(
async with self.session_maker() as session:
stmt = select(schemas.ProjectORM)
stmt = stmt.where(schemas.ProjectORM.id.in_(project_ids))
stmt = stmt.limit(per_page).offset((page - 1) * per_page)
stmt = stmt.limit(per_page).offset(offset)
stmt = stmt.order_by(schemas.ProjectORM.creation_date.desc())
result = await session.execute(stmt)
projects_orm = result.scalars().all()
Expand Down

0 comments on commit 78e9e49

Please sign in to comment.