Skip to content

Instantly share code, notes, and snippets.

@dan-osull
Created June 3, 2022 15:54
Show Gist options
  • Save dan-osull/86d0ee67b0a4af3ad33153b2390c3123 to your computer and use it in GitHub Desktop.
Save dan-osull/86d0ee67b0a4af3ad33153b2390c3123 to your computer and use it in GitHub Desktop.
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