Created
June 3, 2022 15:54
-
-
Save dan-osull/86d0ee67b0a4af3ad33153b2390c3123 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Companion blog post here: https://blog.osull.com/2022/06/03/a-very-simple-async-response-cache-for-fastapi/