Skip to content

Instantly share code, notes, and snippets.

Created June 3, 2022 15:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
app = FastAPI()
async def example():
return {"message": "Hello World"}
response = None
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)
async def home_page(request: Request):
await asyncio.sleep(2)
return templates.TemplateResponse("hello_world.html", context={"request": request})
async def json_example():
await asyncio.sleep(2)
return {"message": "Hello World"}
Copy link

dan-osull commented Oct 28, 2022

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