Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import asyncio
from functools import wraps
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
def cache_response(func):
"""
Decorator that caches the response of a FastAPI async function.
Example:
```
app = FastAPI()
@app.get("/")
@cache_response
async def example():
return {"message": "Hello World"}
```
"""
response = None
@wraps(func)
async def wrapper(*args, **kwargs):
nonlocal response
if not response:
response = await func(*args, **kwargs)
return response
return wrapper
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
@cache_response
async def home_page(request: Request):
await asyncio.sleep(2)
return templates.TemplateResponse("hello_world.html", context={"request": request})
@app.get("/json/")
@cache_response
async def json_example():
await asyncio.sleep(2)
return {"message": "Hello World"}
@dan-osull
Copy link
Author

dan-osull commented Oct 28, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment