Skip to content

Commit

Permalink
Merge pull request #101 from observerly/feature/config/RedisBackend
Browse files Browse the repository at this point in the history
feat: Amended aioredis @app.on_event("startup") to only initialise FastAPICache if specified.
  • Loading branch information
michealroberts committed Feb 13, 2023
2 parents 4018b38 + 710740d commit b6564eb
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 10 deletions.
4 changes: 0 additions & 4 deletions app/api/api_v1/endpoints/bodies.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from typing import Any, Optional

from fastapi import APIRouter, Depends, Request, Response
from fastapi_cache.coder import PickleCoder
from fastapi_cache.decorator import cache
from sqlalchemy.orm import Session

from app import crud, schemas
Expand All @@ -14,7 +12,6 @@


@router.get("/", name="bodies:list", response_model=PaginatedResponse[schemas.Body])
@cache(expire=31556952, namespace="perseus:bodies:list", coder=PickleCoder)
async def list_bodies(
req: Request,
response: Response,
Expand Down Expand Up @@ -50,7 +47,6 @@ async def list_bodies(
name="bodies:list-paginated",
response_model=PaginatedResponse[schemas.Body],
)
@cache(expire=31556952, namespace="perseus:bodies:list-paginated", coder=PickleCoder)
async def list_bodies_paginated(
req: Request,
response: Response,
Expand Down
4 changes: 2 additions & 2 deletions app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ def assemble_cloudrun_service_url(cls, v: Optional[str]) -> Optional[str]:
REDIS_DSN: Optional[str] = None

@validator("REDIS_DSN", pre=True)
def assemble_redis_dsn(cls, v: str, values: Dict[str, Any]) -> str:
def assemble_redis_dsn(cls, v: str, values: Dict[str, Any]) -> Optional[str]:
if isinstance(v, str):
return v
return "redis://redis"
return None

SENTRY_DSN: Optional[HttpUrl]

Expand Down
12 changes: 8 additions & 4 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from fastapi.responses import ORJSONResponse, RedirectResponse
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.coder import PickleCoder
from redis import asyncio as aioredis
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

Expand Down Expand Up @@ -88,10 +89,13 @@ async def add_custom_x_headers(request: Request, call_next):

@app.on_event("startup")
async def startup():
try:
if settings.REDIS_DSN:
redis = aioredis.from_url(
settings.REDIS_DSN, encoding="utf8", decode_responses=True
)
FastAPICache.init(RedisBackend(redis), prefix="perseus-cache")
except Exception as e:
print(e)
FastAPICache.init(
RedisBackend(redis),
prefix="perseus-cache",
expire=31556952,
coder=PickleCoder,
)

0 comments on commit b6564eb

Please sign in to comment.