Add in-memory support.

This commit is contained in:
long2ice
2020-10-08 15:10:34 +08:00
parent 800032c46b
commit c0259bc699
8 changed files with 236 additions and 202 deletions

View File

@@ -11,7 +11,7 @@
## Features
- Support `redis` and `memcache` .
- Support `redis` and `memcache` and `in-memory` backends.
- Easily integration with `fastapi`.
- Support http cache like `ETag` and `Cache-Control`.
@@ -23,6 +23,12 @@
## Install
```shell
> pip install fastapi-cache2
```
or
```shell
> pip install fastapi-cache2[redis]
```
@@ -39,14 +45,13 @@ or
```python
import aioredis
import uvicorn
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache_response, cache
from fastapi_cache.decorator import cache
app = FastAPI()
@@ -57,7 +62,7 @@ async def get_cache():
@app.get("/")
@cache_response(expire=60)
@cache(expire=60)
async def index(request: Request, response: Response):
return dict(hello="world")
@@ -69,15 +74,13 @@ async def startup():
```
### Use `cache_response`
### Use `cache` decorator
If you want cache `fastapi` response transparently, you can use `cache_response` as decorator between router decorator and view function and must pass `request` as param of view function.
If you want cache `fastapi` response transparently, you can use `cache` as decorator between router decorator and view function and must pass `request` as param of view function.
And if you want use `ETag` and `Cache-Control` features, you must pass `response` param also.
### Use `cache`
You can use `cache` as decorator like other cache tools to cache common function result.
You can also use `cache` as decorator like other cache tools to cache common function result.
### Custom coder
@@ -85,7 +88,7 @@ By default use `JsonCoder`, you can write custom coder to encode and decode cach
```python
@app.get("/")
@cache_response(expire=60,coder=JsonCoder)
@cache(expire=60,coder=JsonCoder)
async def index(request: Request, response: Response):
return dict(hello="world")
```
@@ -106,11 +109,15 @@ def my_key_builder(
return cache_key
@app.get("/")
@cache_response(expire=60,coder=JsonCoder,key_builder=my_key_builder)
@cache(expire=60,coder=JsonCoder,key_builder=my_key_builder)
async def index(request: Request, response: Response):
return dict(hello="world")
```
### InMemoryBackend
`InMemoryBackend` only support in single node instead of distributed environment.
## License
This project is licensed under the [Apache-2.0](https://github.com/long2ice/fastapi-cache/blob/master/LICENSE) License.