refactor: pagination total pages

main
MrWaradana 1 year ago
parent 1688061eb8
commit 277d48d03b

10
poetry.lock generated

@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand. # This file is automatically @generated by Poetry 1.8.5 and should not be changed by hand.
[[package]] [[package]]
name = "annotated-types" name = "annotated-types"
@ -331,13 +331,13 @@ typing-extensions = "*"
[[package]] [[package]]
name = "fastapi" name = "fastapi"
version = "0.115.5" version = "0.115.6"
description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"
optional = false optional = false
python-versions = ">=3.8" python-versions = ">=3.8"
files = [ files = [
{file = "fastapi-0.115.5-py3-none-any.whl", hash = "sha256:596b95adbe1474da47049e802f9a65ab2ffa9c2b07e7efee70eb8a66c9f2f796"}, {file = "fastapi-0.115.6-py3-none-any.whl", hash = "sha256:e9240b29e36fa8f4bb7290316988e90c381e5092e0cbe84e7818cc3713bcf305"},
{file = "fastapi-0.115.5.tar.gz", hash = "sha256:0e7a4d0dc0d01c68df21887cce0945e72d3c48b9f4f79dfe7a7d53aa08fbb289"}, {file = "fastapi-0.115.6.tar.gz", hash = "sha256:9ec46f7addc14ea472958a96aae5b5de65f39721a46aaf5705c480d9a8b76654"},
] ]
[package.dependencies] [package.dependencies]
@ -1754,4 +1754,4 @@ files = [
[metadata] [metadata]
lock-version = "2.0" lock-version = "2.0"
python-versions = "^3.11" python-versions = "^3.11"
content-hash = "b93e353c3127c9a775c97c87cdb05d476a920729ad29150a4273a079ef14733a" content-hash = "9654447dbf1475e6cc8b087b55d5c8b79d8427983634bed31405ebd0bb9ddc91"

@ -8,7 +8,7 @@ readme = "README.md"
[tool.poetry.dependencies] [tool.poetry.dependencies]
python = "^3.11" python = "^3.11"
fastapi = {extras = ["standard"], version = "^0.115.4"} fastapi = {extras = ["standard"], version = "^0.115.6"}
sqlalchemy = "^2.0.36" sqlalchemy = "^2.0.36"
httpx = "^0.27.2" httpx = "^0.27.2"
pytest = "^8.3.3" pytest = "^8.3.3"

@ -1,4 +1,3 @@
import logging import logging
from typing import Annotated, List from typing import Annotated, List
@ -42,8 +41,7 @@ def common_parameters(
CommonParameters = Annotated[ CommonParameters = Annotated[
dict[str, int | str | DbSession | QueryStr | dict[str, int | str | DbSession | QueryStr | Json | List[str] | List[bool]],
Json | List[str] | List[bool]],
Depends(common_parameters), Depends(common_parameters),
] ]
@ -72,8 +70,7 @@ def search(*, query_str: str, query: Query, model, sort=False):
query = query.filter(or_(*search)) query = query.filter(or_(*search))
if sort: if sort:
query = query.order_by( query = query.order_by(desc(func.ts_rank_cd(vector, func.tsq_parse(query_str))))
desc(func.ts_rank_cd(vector, func.tsq_parse(query_str))))
return query.params(term=query_str) return query.params(term=query_str)
@ -99,18 +96,13 @@ async def search_filter_sort_paginate(
if query_str: if query_str:
sort = False if sort_by else True sort = False if sort_by else True
query = search(query_str=query_str, query=query, query = search(query_str=query_str, query=query, model=model, sort=sort)
model=model, sort=sort)
# Get total count # Get total count
count_query = Select(func.count()).select_from(query.subquery()) count_query = Select(func.count()).select_from(query.subquery())
total = await db_session.scalar(count_query) total = await db_session.scalar(count_query)
query = ( query = query.offset((page - 1) * items_per_page).limit(items_per_page)
query
.offset((page - 1) * items_per_page)
.limit(items_per_page)
)
result = await db_session.execute(query) result = await db_session.execute(query)
items = result.scalars().all() items = result.scalars().all()

@ -11,6 +11,7 @@ import pytz
from src.auth.service import CurrentUser from src.auth.service import CurrentUser
from src.enums import ResponseStatus from src.enums import ResponseStatus
# SQLAlchemy Mixins # SQLAlchemy Mixins
@ -18,10 +19,12 @@ class TimeStampMixin(object):
"""Timestamping mixin""" """Timestamping mixin"""
created_at = Column( created_at = Column(
DateTime(timezone=True), default=datetime.now(pytz.timezone(TIMEZONE))) DateTime(timezone=True), default=datetime.now(pytz.timezone(TIMEZONE))
)
created_at._creation_order = 9998 created_at._creation_order = 9998
updated_at = Column( updated_at = Column(
DateTime(timezone=True), default=datetime.now(pytz.timezone(TIMEZONE))) DateTime(timezone=True), default=datetime.now(pytz.timezone(TIMEZONE))
)
updated_at._creation_order = 9998 updated_at._creation_order = 9998
@staticmethod @staticmethod
@ -35,18 +38,26 @@ class TimeStampMixin(object):
class UUIDMixin: class UUIDMixin:
"""UUID mixin""" """UUID mixin"""
id = Column(UUID(as_uuid=True), primary_key=True,
default=uuid.uuid4, unique=True, nullable=False) id = Column(
UUID(as_uuid=True),
primary_key=True,
default=uuid.uuid4,
unique=True,
nullable=False,
)
class IdentityMixin: class IdentityMixin:
"""Identity mixin""" """Identity mixin"""
created_by = Column(String(100), nullable=True) created_by = Column(String(100), nullable=True)
updated_by = Column(String(100), nullable=True) updated_by = Column(String(100), nullable=True)
class DefaultMixin(TimeStampMixin, UUIDMixin): class DefaultMixin(TimeStampMixin, UUIDMixin):
"""Default mixin""" """Default mixin"""
pass pass
@ -69,6 +80,7 @@ class Pagination(DefultBase):
itemsPerPage: int itemsPerPage: int
page: int page: int
total: int total: int
totalPages: int
class PrimaryKeyModel(BaseModel): class PrimaryKeyModel(BaseModel):
@ -76,7 +88,7 @@ class PrimaryKeyModel(BaseModel):
# Define data type variable for generic response # Define data type variable for generic response
T = TypeVar('T') T = TypeVar("T")
class StandardResponse(BaseModel, Generic[T]): class StandardResponse(BaseModel, Generic[T]):

Loading…
Cancel
Save