1010from fastapi .staticfiles import StaticFiles
1111from fastapi .templating import Jinja2Templates
1212from fastapi_cache import FastAPICache
13- from fastapi_cache .backends .redis import RedisBackend
13+ from fastapi_cache .backends .valkey import ValkeyBackend
1414from fastapi_cache .coder import PickleCoder
1515from fastapi_cache .decorator import cache
1616from starlette .requests import Request
1717from starlette .responses import JSONResponse , Response
1818
19- import redis .asyncio as redis
20- from redis .asyncio .connection import ConnectionPool
19+ from valkey .asyncio import Valkey
2120
2221
2322@asynccontextmanager
2423async def lifespan (_ : FastAPI ) -> AsyncIterator [None ]:
25- pool = ConnectionPool .from_url (url = "redis://redis" )
26- r = redis .Redis (connection_pool = pool )
27- FastAPICache .init (RedisBackend (r ), prefix = "fastapi-cache" )
24+ client = Valkey (
25+ host = "localhost" ,
26+ port = 6379 ,
27+ db = 0 ,
28+ decode_responses = False ,
29+ )
30+
31+ # Test the connection
32+ try :
33+ await client .ping ()
34+ print (f"✓ Connected to Valkey at localhost:6379" )
35+ except Exception as e :
36+ print (f"✗ Failed to connect to Valkey: { e } " )
37+ raise
38+
39+ FastAPICache .init (ValkeyBackend (client ), prefix = "fastapi-cache" )
40+
2841 yield
42+
43+ print ("Closing Valkey connection..." )
44+ await client .close ()
2945
3046
3147app = FastAPI (lifespan = lifespan )
@@ -63,10 +79,9 @@ async def get_data(request: Request, response: Response):
6379 return pendulum .today ()
6480
6581
66- # Note: This function MUST be sync to demonstrate fastapi-cache's correct handling,
67- # i.e. running cached sync functions in threadpool just like FastAPI itself!
82+ # MUST be sync to verify threadpool + cache handling
6883@app .get ("/blocking" )
69- @cache (namespace = "test" , expire = 10 ) # pyright: ignore[reportArgumentType]
84+ @cache (namespace = "test" , expire = 10 ) # pyright: ignore[reportArgumentType]
7085def blocking ():
7186 time .sleep (2 )
7287 return {"ret" : 42 }
@@ -82,7 +97,9 @@ async def get_datetime(request: Request, response: Response):
8297@app .get ("/html" , response_class = HTMLResponse )
8398@cache (expire = 60 , namespace = "html" , coder = PickleCoder )
8499async def cache_html (request : Request ):
85- return templates .TemplateResponse ("index.html" , {"request" : request , "ret" : await get_ret ()})
100+ return templates .TemplateResponse (
101+ "index.html" , {"request" : request , "ret" : await get_ret ()}
102+ )
86103
87104
88105@app .get ("/cache_response_obj" )
@@ -92,4 +109,4 @@ async def cache_response_obj():
92109
93110
94111if __name__ == "__main__" :
95- uvicorn .run ("main:app" , reload = True )
112+ uvicorn .run ("main:app" , reload = True )
0 commit comments