-
-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathmain.py
More file actions
152 lines (105 loc) · 3.6 KB
/
Copy pathmain.py
File metadata and controls
152 lines (105 loc) · 3.6 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# pyright: reportGeneralTypeIssues=false
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Dict, Optional
import pendulum
import uvicorn
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend
from fastapi_cache.decorator import cache
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
FastAPICache.init(InMemoryBackend())
yield
app = FastAPI(lifespan=lifespan)
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_date():
return pendulum.today()
@app.get("/datetime")
@cache(namespace="test", expire=2)
async def get_datetime(request: Request, response: Response):
return {"now": pendulum.now()}
@cache(namespace="test")
async def func_kwargs(*unused_args, **kwargs):
return kwargs
@app.get("/kwargs")
async def get_kwargs(name: str):
return await func_kwargs(name, name=name)
@app.get("/sync-me")
@cache(namespace="test") # pyright: ignore[reportArgumentType]
def sync_me():
# as per the fastapi docs, this sync function is wrapped in a thread,
# thereby converted to async. fastapi-cache does the same.
return 42
@app.get("/cache_response_obj")
@cache(namespace="test", expire=5)
async def cache_response_obj():
return JSONResponse({"a": 1})
class SomeClass:
def __init__(self, value):
self.value = value
async def handler_method(self):
return self.value
# register an instance method as a handler
instance = SomeClass(17)
app.get("/method")(cache(namespace="test")(instance.handler_method))
# cache a Pydantic model instance; the return type annotation is required in this case
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.get("/pydantic_instance")
@cache(namespace="test", expire=5)
async def pydantic_instance() -> Item:
return Item(name="Something", description="An instance of a Pydantic model", price=10.5)
put_ret = 0
@app.put("/uncached_put")
@cache(namespace="test", expire=5)
async def uncached_put():
global put_ret
put_ret = put_ret + 1
return {"value": put_ret}
put_ret2 = 0
@app.get("/cached_put")
@cache(namespace="test", expire=5)
async def cached_put():
global put_ret2
put_ret2 = put_ret2 + 1
return {"value": put_ret2}
@app.get("/namespaced_injection")
@cache(namespace="test", expire=5, injected_dependency_namespace="monty_python") # pyright: ignore[reportArgumentType]
def namespaced_injection(
__fastapi_cache_request: int = 42, __fastapi_cache_response: int = 17
) -> Dict[str, int]:
return {
"__fastapi_cache_request": __fastapi_cache_request,
"__fastapi_cache_response": __fastapi_cache_response,
}
exclude_ret = 0
@app.get("/excluded_params")
@cache(namespace="test", expire=5, exclude_params=["nonce"])
async def excluded_params(name: str, nonce: str = "") -> Dict[str, Any]:
# calls that only differ in `nonce` all share one cache entry
global exclude_ret
exclude_ret = exclude_ret + 1
return {"name": name, "nonce": nonce, "value": exclude_ret}
if __name__ == "__main__":
uvicorn.run("main:app", reload=True)