feat: support cache jinja2 template response

This commit is contained in:
vvanglro
2022-09-28 17:37:05 +08:00
parent 34415ad50a
commit 7e64cd6490
5 changed files with 35 additions and 2 deletions

View File

@@ -2,6 +2,10 @@
## 0.2 ## 0.2
### 0.2.1
- Support cache jinja2 template response.
### 0.2.0 ### 0.2.0
- Make `request` and `response` optional. - Make `request` and `response` optional.

10
examples/redis/index.html Normal file
View File

@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Cache HTML! {{ ret }} </h1>
</body>
</html>

View File

@@ -7,13 +7,21 @@ from fastapi import FastAPI
from redis.asyncio.connection import ConnectionPool from redis.asyncio.connection import ConnectionPool
from starlette.requests import Request from starlette.requests import Request
from starlette.responses import Response from starlette.responses import Response
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi_cache import FastAPICache from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.coder import PickleCoder
from fastapi_cache.decorator import cache from fastapi_cache.decorator import cache
app = FastAPI() app = FastAPI()
app.mount(
path='/static',
app=StaticFiles(directory='./'), name='static',
)
templates = Jinja2Templates(directory='./')
ret = 0 ret = 0
@@ -55,6 +63,14 @@ async def get_datetime(request: Request, response: Response):
return pendulum.now() 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.on_event("startup") @app.on_event("startup")
async def startup(): async def startup():
pool = ConnectionPool.from_url(url="redis://redis") pool = ConnectionPool.from_url(url="redis://redis")

View File

@@ -6,6 +6,7 @@ from typing import Any
import pendulum import pendulum
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from starlette.templating import _TemplateResponse as TemplateResponse
CONVERTERS = { CONVERTERS = {
"date": lambda x: pendulum.parse(x, exact=True), "date": lambda x: pendulum.parse(x, exact=True),
@@ -60,6 +61,8 @@ class JsonCoder(Coder):
class PickleCoder(Coder): class PickleCoder(Coder):
@classmethod @classmethod
def encode(cls, value: Any): def encode(cls, value: Any):
if isinstance(value, TemplateResponse):
value = value.body
return pickle.dumps(value) return pickle.dumps(value)
@classmethod @classmethod

View File

@@ -1,6 +1,6 @@
[tool.poetry] [tool.poetry]
name = "fastapi-cache2" name = "fastapi-cache2"
version = "0.2.0" version = "0.2.1"
description = "Cache for FastAPI" description = "Cache for FastAPI"
authors = ["long2ice <long2ice@gmail.com>"] authors = ["long2ice <long2ice@gmail.com>"]
license = "Apache-2.0" license = "Apache-2.0"