Skip to content

Commit 0e3a4fe

Browse files
committed
add cache
1 parent e1f1618 commit 0e3a4fe

3 files changed

Lines changed: 19 additions & 4 deletions

File tree

api_v1/users/views.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from fastapi import APIRouter, Depends
22
from fastapi_users import FastAPIUsers
3+
from fastapi_cache.decorator import cache
34

45
from config.models import User
56
from api_v1.auth.backends import auth_backend
@@ -18,11 +19,11 @@
1819

1920

2021
@router.get(path='/test',
21-
response_model=UserRead,
2222
dependencies=[Depends(active_user)],
2323
)
24+
@cache()
2425
async def test_end_point(user: User = Depends(active_user)):
25-
return user
26+
return dict(name=user.email)
2627

2728

2829
router.include_router(fastapi_users.get_users_router(UserRead, UserUpdate),

main.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
from contextlib import asynccontextmanager
22
from fastapi import FastAPI
3+
from fastapi_cache import FastAPICache
4+
from fastapi_cache.backends.redis import RedisBackend
5+
from fastapi_cache.decorator import cache
6+
7+
from redis import asyncio as aioredis
38

49
from api_v1 import register_routers
510
from app_includes import (
611
register_errors,
712
register_middlewares,
813
register_prometheus,
914
)
15+
from config import settings
1016

1117

1218
def start_app() -> FastAPI:
@@ -23,7 +29,15 @@ def start_app() -> FastAPI:
2329

2430
@asynccontextmanager
2531
async def lifespan(app: FastAPI):
32+
redis = aioredis.from_url(settings.redis.redis_url)
33+
FastAPICache.init(RedisBackend(redis), prefix='fastapi-cache')
2634
yield
2735

2836

2937
app = start_app()
38+
39+
40+
@app.get(path='/test')
41+
@cache()
42+
async def test_end_point():
43+
return dict(hello='world')

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ alembic = "^1.14.0"
2020
pytest = "^8.3.3"
2121
prometheus-fastapi-instrumentator = "^7.0.0"
2222
fastapi-users = {extras = ["sqlalchemy"], version = "^14.0.0"}
23-
redis = "^5.2.1"
24-
aioredis = "^2.0.1"
23+
redis = {extras = ["redis"], version = "^5.2.1"}
24+
fastapi-cache2 = "^0.2.2"
2525

2626

2727
[tool.poetry.group.dev.dependencies]

0 commit comments

Comments
 (0)