-
-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (70 loc) · 2.44 KB
/
Copy pathmain.py
File metadata and controls
94 lines (70 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# pyright: reportGeneralTypeIssues=false
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
import pendulum
import redis.asyncio as redis
import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.coder import PickleCoder
from fastapi_cache.decorator import cache
from redis.asyncio.connection import ConnectionPool
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
pool = ConnectionPool.from_url(url="redis://redis")
r = redis.Redis(connection_pool=pool)
FastAPICache.init(RedisBackend(r), prefix="fastapi-cache")
yield
app = FastAPI(lifespan=lifespan)
app.mount(
path="/static",
app=StaticFiles(directory="./"),
name="static",
)
templates = Jinja2Templates(directory="./")
ret = 0
@cache(namespace="test", expire=1)
async def get_ret():
global ret
ret = ret + 1
return ret
@app.get("/")
@cache(namespace="test", expire=10)
async def index():
return {"ret": await get_ret()}
@app.get("/clear")
async def clear():
return await FastAPICache.clear(namespace="test")
@app.get("/date")
@cache(namespace="test", expire=10)
async def get_data(request: Request, response: Response):
return pendulum.today()
# Note: This function MUST be sync to demonstrate fastapi-cache's correct handling,
# i.e. running cached sync functions in threadpool just like FastAPI itself!
@app.get("/blocking")
@cache(namespace="test", expire=10) # pyright: ignore[reportArgumentType]
def blocking():
time.sleep(2)
return {"ret": 42}
@app.get("/datetime")
@cache(namespace="test", expire=2)
async def get_datetime(request: Request, response: Response):
print(request, response)
return pendulum.now()
@app.get("/html", response_class=HTMLResponse)
@cache(expire=60, namespace="html", coder=PickleCoder)
async def cache_html(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "ret": await get_ret()})
@app.get("/cache_response_obj")
@cache(namespace="test", expire=5)
async def cache_response_obj():
return JSONResponse({"a": 1})
if __name__ == "__main__":
uvicorn.run("main:app", reload=True)