Skip to content

Commit

Permalink
++
Browse files Browse the repository at this point in the history
# Conflicts:
#	backend/bloom/routers/v1/vessels.py
  • Loading branch information
herve.le-bars committed Nov 10, 2024
1 parent 491fbc2 commit ada0bcc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
15 changes: 13 additions & 2 deletions backend/bloom/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
from fastapi import Request, HTTPException
from fastapi import Request, HTTPException, Depends
from bloom.config import settings
from fastapi.security import APIKeyHeader
from pydantic import BaseModel, ConfigDict, Field,conint
from pydantic.generics import GenericModel
from datetime import datetime, timedelta
from typing import Generic,TypeVar, List
from typing import Generic,TypeVar, List, Annotated
from enum import Enum
from bloom.container import UseCases
import redis



UserCasesDep= Annotated[UseCases, Depends(UseCases)]
CacheServiceDep= Annotated[redis.Redis, Depends(UseCases.service_cache)]

## Reference for pagination design
## https://jayhawk24.hashnode.dev/how-to-implement-pagination-in-fastapi-feat-sqlalchemy
X_API_KEY_HEADER=APIKeyHeader(name="x-key")

class CachedRequest(BaseModel):
nocache:bool=False




def check_apikey(key:str):
if key != settings.api_key :
raise HTTPException(status_code=401, detail="Unauthorized")
Expand Down Expand Up @@ -42,6 +51,7 @@ class PaginatedRequest(BaseModel):
order_by: OrderByRequest = OrderByEnum.ascending



class PageParams(BaseModel):
""" Request query params for paginated API. """
offset: conint(ge=0) = 0
Expand All @@ -57,6 +67,7 @@ class PagedResponseSchema(GenericModel,Generic[T]):
previous: str|None
results: List[T]


def paginate(request: Request, page_params: PageParams, query, ResponseSchema: BaseModel) -> PagedResponseSchema[T]:
"""Paginate the query."""

Expand Down
16 changes: 10 additions & 6 deletions backend/bloom/routers/v1/vessels.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,20 @@
X_API_KEY_HEADER,check_apikey)

router = APIRouter()
rd = redis.Redis(host=settings.redis_host, port=settings.redis_port, db=0, password=settings.redis_password)
#rd = redis.Redis(host=settings.redis_host, port=settings.redis_port, db=0)

UserCasesDep= Annotated[UseCases, Depends(UseCases)]
CacheServiceDep= Annotated[redis.Redis, Depends(UseCases.service_cache)]

@router.get("/vessels")
async def list_vessels(request: Request,
nocache:bool=False,
key: str = Depends(X_API_KEY_HEADER)):
use_cases = UseCases()
key: str = Depends(X_API_KEY_HEADER),
use_cases = UserCasesDep,
cache_service=CacheServiceDep):
check_apikey(key)
cache_key=f"{request.url.path}"
cache= use_cases.service_cache().get(cache_key)
cache= cache_service.get(cache_key)
start = time.time()
if cache and not nocache:
logger.debug(f"{cache_key} cached ({settings.redis_cache_expiration})s")
Expand All @@ -44,8 +48,8 @@ async def list_vessels(request: Request,

json_data = [json.loads(v.model_dump_json() if v else "{}")
for v in vessel_repository.get_vessels_list(session)]
rd.set(cache_key, json.dumps(json_data))
rd.expire(cache_key,settings.redis_cache_expiration)
cache_service.set(cache_key, json.dumps(json_data))
cache_service.expire(cache_key,settings.redis_cache_expiration)
return json_data

@router.get("/vessels/{vessel_id}")
Expand Down

0 comments on commit ada0bcc

Please sign in to comment.