# fastapi-cache
![pypi](https://img.shields.io/pypi/v/fastapi-cache2.svg?style=flat)
![license](https://img.shields.io/github/license/long2ice/fastapi-cache)
![workflows](https://github.com/long2ice/fastapi-cache/workflows/pypi/badge.svg)
![workflows](https://github.com/long2ice/fastapi-cache/workflows/ci/badge.svg)
## Introduction
`fastapi-cache` is a tool to cache fastapi response and function result, with backends support `redis`, `memcache`,
and `dynamodb`.
## Features
- Support `redis`, `memcache`, `dynamodb`, and `in-memory` backends.
- Easily integration with `fastapi`.
- Support http cache like `ETag` and `Cache-Control`.
## Requirements
- `asyncio` environment.
- `redis` if use `RedisBackend`.
- `memcache` if use `MemcacheBackend`.
- `aiobotocore` if use `DynamoBackend`.
## Install
```shell
> pip install fastapi-cache2
```
or
```shell
> pip install "fastapi-cache2[redis]"
```
or
```shell
> pip install "fastapi-cache2[memcache]"
```
or
```shell
> pip install "fastapi-cache2[dynamodb]"
```
## Usage
### Quick Start
```python
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
from redis import asyncio as aioredis
app = FastAPI()
@cache()
async def get_cache():
return 1
@app.get("/")
@cache(expire=60)
async def index():
return dict(hello="world")
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost", encoding="utf8", decode_responses=True)
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
```
### Initialization
Firstly you must call `FastAPICache.init` on startup event of `fastapi`, there are some global config you can pass in.
### Use `cache` decorator
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.
Parameter | type, description
------------ | -------------
expire | int, states a caching time in seconds
namespace | str, namespace to use to store certain cache items
coder | which coder to use, e.g. JsonCoder
key_builder | which key builder to use, default to builtin
You can also use `cache` as decorator like other cache tools to cache common function result.
### Custom coder
By default use `JsonCoder`, you can write custom coder to encode and decode cache result, just need
inherit `fastapi_cache.coder.Coder`.
```python
@app.get("/")
@cache(expire=60, coder=JsonCoder)
async def index():
return dict(hello="world")
```
### Custom key builder
By default use builtin key builder, if you need, you can override this and pass in `cache` or `FastAPICache.init` to
take effect globally.
```python
def my_key_builder(
func,
namespace: Optional[str] = "",
request: Request = None,
response: Response = None,
*args,
**kwargs,
):
prefix = FastAPICache.get_prefix()
cache_key = f"{prefix}:{namespace}:{func.__module__}:{func.__name__}:{args}:{kwargs}"
return cache_key
@app.get("/")
@cache(expire=60, coder=JsonCoder, key_builder=my_key_builder)
async def index():
return dict(hello="world")
```
### InMemoryBackend
`InMemoryBackend` store cache data in memory and use lazy delete, which mean if you don't access it after cached, it
will not delete automatically.
## Tests and coverage
```shell
coverage run -m pytest
coverage html
xdg-open htmlcov/index.html
```
## License
This project is licensed under the [Apache-2.0](https://github.com/long2ice/fastapi-cache/blob/master/LICENSE) License.
Raw data
{
"_id": null,
"home_page": "https://github.com/long2ice/fastapi-cache",
"name": "fastapi-cache2",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.7,<4.0",
"maintainer_email": "",
"keywords": "fastapi,cache,caching",
"author": "long2ice",
"author_email": "long2ice@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/66/9f/92e57cc36bf648c440bd811e74fea82638be5f108086de91f6235d41e5f5/fastapi-cache2-0.2.0.tar.gz",
"platform": null,
"description": "# fastapi-cache\n\n![pypi](https://img.shields.io/pypi/v/fastapi-cache2.svg?style=flat)\n![license](https://img.shields.io/github/license/long2ice/fastapi-cache)\n![workflows](https://github.com/long2ice/fastapi-cache/workflows/pypi/badge.svg)\n![workflows](https://github.com/long2ice/fastapi-cache/workflows/ci/badge.svg)\n\n## Introduction\n\n`fastapi-cache` is a tool to cache fastapi response and function result, with backends support `redis`, `memcache`,\nand `dynamodb`.\n\n## Features\n\n- Support `redis`, `memcache`, `dynamodb`, and `in-memory` backends.\n- Easily integration with `fastapi`.\n- Support http cache like `ETag` and `Cache-Control`.\n\n## Requirements\n\n- `asyncio` environment.\n- `redis` if use `RedisBackend`.\n- `memcache` if use `MemcacheBackend`.\n- `aiobotocore` if use `DynamoBackend`.\n\n## Install\n\n```shell\n> pip install fastapi-cache2\n```\n\nor\n\n```shell\n> pip install \"fastapi-cache2[redis]\"\n```\n\nor\n\n```shell\n> pip install \"fastapi-cache2[memcache]\"\n```\n\nor\n\n```shell\n> pip install \"fastapi-cache2[dynamodb]\"\n```\n\n## Usage\n\n### Quick Start\n\n```python\nfrom fastapi import FastAPI\nfrom starlette.requests import Request\nfrom starlette.responses import Response\n\nfrom fastapi_cache import FastAPICache\nfrom fastapi_cache.backends.redis import RedisBackend\nfrom fastapi_cache.decorator import cache\n\nfrom redis import asyncio as aioredis\n\napp = FastAPI()\n\n\n@cache()\nasync def get_cache():\n return 1\n\n\n@app.get(\"/\")\n@cache(expire=60)\nasync def index():\n return dict(hello=\"world\")\n\n\n@app.on_event(\"startup\")\nasync def startup():\n redis = aioredis.from_url(\"redis://localhost\", encoding=\"utf8\", decode_responses=True)\n FastAPICache.init(RedisBackend(redis), prefix=\"fastapi-cache\")\n\n```\n\n### Initialization\n\nFirstly you must call `FastAPICache.init` on startup event of `fastapi`, there are some global config you can pass in.\n\n### Use `cache` decorator\n\nIf you want cache `fastapi` response transparently, you can use `cache` as decorator between router decorator and view\nfunction and must pass `request` as param of view function.\n\nParameter | type, description\n------------ | -------------\nexpire | int, states a caching time in seconds\nnamespace | str, namespace to use to store certain cache items\ncoder | which coder to use, e.g. JsonCoder\nkey_builder | which key builder to use, default to builtin\n\nYou can also use `cache` as decorator like other cache tools to cache common function result.\n\n### Custom coder\n\nBy default use `JsonCoder`, you can write custom coder to encode and decode cache result, just need\ninherit `fastapi_cache.coder.Coder`.\n\n```python\n@app.get(\"/\")\n@cache(expire=60, coder=JsonCoder)\nasync def index():\n return dict(hello=\"world\")\n```\n\n### Custom key builder\n\nBy default use builtin key builder, if you need, you can override this and pass in `cache` or `FastAPICache.init` to\ntake effect globally.\n\n```python\ndef my_key_builder(\n func,\n namespace: Optional[str] = \"\",\n request: Request = None,\n response: Response = None,\n *args,\n **kwargs,\n):\n prefix = FastAPICache.get_prefix()\n cache_key = f\"{prefix}:{namespace}:{func.__module__}:{func.__name__}:{args}:{kwargs}\"\n return cache_key\n\n\n@app.get(\"/\")\n@cache(expire=60, coder=JsonCoder, key_builder=my_key_builder)\nasync def index():\n return dict(hello=\"world\")\n```\n\n### InMemoryBackend\n\n`InMemoryBackend` store cache data in memory and use lazy delete, which mean if you don't access it after cached, it\nwill not delete automatically.\n\n## Tests and coverage\n\n```shell\ncoverage run -m pytest\ncoverage html\nxdg-open htmlcov/index.html\n```\n\n## License\n\nThis project is licensed under the [Apache-2.0](https://github.com/long2ice/fastapi-cache/blob/master/LICENSE) License.\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Cache for FastAPI",
"version": "0.2.0",
"split_keywords": [
"fastapi",
"cache",
"caching"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "ca0b1880dd07c3cf544712eaf9f9d2981d8b8c8c8a8889a522db8bb687469004",
"md5": "3816b18cb95b81f88253fe11f84a41ff",
"sha256": "cc4901bcf370849c33a46cf405c828cb19401f842bdbd804d0e8be2b353e3414"
},
"downloads": -1,
"filename": "fastapi_cache2-0.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "3816b18cb95b81f88253fe11f84a41ff",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7,<4.0",
"size": 19942,
"upload_time": "2023-01-11T13:23:36",
"upload_time_iso_8601": "2023-01-11T13:23:36.568190Z",
"url": "https://files.pythonhosted.org/packages/ca/0b/1880dd07c3cf544712eaf9f9d2981d8b8c8c8a8889a522db8bb687469004/fastapi_cache2-0.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "669f92e57cc36bf648c440bd811e74fea82638be5f108086de91f6235d41e5f5",
"md5": "b4b609f56ab5bd731494f0b309ea9695",
"sha256": "b3f3fc722e6b454016cd04e9b3a3a6201371cf86b5f75f86ce4be864d390495b"
},
"downloads": -1,
"filename": "fastapi-cache2-0.2.0.tar.gz",
"has_sig": false,
"md5_digest": "b4b609f56ab5bd731494f0b309ea9695",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7,<4.0",
"size": 13210,
"upload_time": "2023-01-11T13:23:37",
"upload_time_iso_8601": "2023-01-11T13:23:37.856865Z",
"url": "https://files.pythonhosted.org/packages/66/9f/92e57cc36bf648c440bd811e74fea82638be5f108086de91f6235d41e5f5/fastapi-cache2-0.2.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-01-11 13:23:37",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "long2ice",
"github_project": "fastapi-cache",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "fastapi-cache2"
}