Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

poc: cache #144

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/api/shakespeare.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession

from fastapi_cache.decorator import cache

from app.database import get_db
from app.models.shakespeare import Paragraph

Expand All @@ -12,6 +14,7 @@
@router.get(
"/",
)
@cache(namespace="test-2", expire=60)
async def find_paragraph(
character: Annotated[str, Query(description="Character name")],
db_session: AsyncSession = Depends(get_db),
Expand Down
13 changes: 11 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
from contextlib import asynccontextmanager

from fastapi import FastAPI, Depends
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend

from app.api.nonsense import router as nonsense_router
from app.api.shakespeare import router as shakespeare_router
from app.api.stuff import router as stuff_router
from app.utils.logging import AppLogger
from app.api.user import router as user_router
from app.api.health import router as health_router
from app.redis import get_redis
from app.redis import get_redis, get_cache
from app.services.auth import AuthBearer

logger = AppLogger().get_logger()
Expand All @@ -18,11 +20,18 @@
async def lifespan(app: FastAPI):
# Load the redis connection
app.state.redis = await get_redis()



try:
# Initialize the cache with the redis connection
redis_cache = await get_cache()
FastAPICache.init(RedisBackend(redis_cache), prefix="fastapi-cache")
logger.info(FastAPICache.get_cache_status_header())
yield
finally:
# close redis connection and release the resources
app.state.redis.close()
await app.state.redis.close()


app = FastAPI(title="Stuff And Nonsense API", version="0.6", lifespan=lifespan)
Expand Down
7 changes: 7 additions & 0 deletions app/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ async def get_redis():
encoding="utf-8",
decode_responses=True,
)


async def get_cache():
return await redis.from_url(
global_settings.redis_url.unicode_string(),
decode_responses=False,
)
Loading
Loading