Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache data in FastAPI?

How can I cache requests in FastAPI?

For example, there are two functions and a PostgreSQL database:

@app.get("/")
def home(request: Request):
  return templates.TemplateResponse("index.html", {"request": request})


@app.post("/api/getData")
async def getData(request: Request, databody = Body()):
  data = databody["data"]
  
  with connection.cursor() as cursor:
       cursor.execute(
              f"INSERT INTO database (ip, useragent, datetime) VALUES ('request.headers['host']', 'request.headers['user-agent']', '{datetime.now()}'")
       )
   return {"req": request}

Then the request is processed by JavaScript and displayed on the HTML page .

like image 411
TASK Avatar asked May 18 '26 16:05

TASK


1 Answers

You can try fastapi-cache:

from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
    
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
    
from redis import asyncio as aioredis
    
app = FastAPI()
    
    
@cache()
async def get_cache():
    return 1
    
    
@app.get("/")
@cache(expire=60)
async def index():
    return dict(hello="world")
    
    
@app.on_event("startup")
async def startup():
   redis = aioredis.from_url("redis://localhost", encoding="utf8", decode_responses=True)
   FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
like image 148
panda912 Avatar answered May 21 '26 05:05

panda912



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!