FastAPICache
Implementation for FastAPI Caching Route.
DEFAULT_ACCEPTED_STATUS_CODES
module-attribute
DEFAULT_ACCEPTED_STATUS_CODES = frozenset({HTTP_200_OK})
FastAPICache
FastAPICache(
cache,
*,
namespace_policy='concat',
cache_header='X-Cache',
cache_header_hit='HIT',
cache_header_miss='MISS',
accepted_status_codes=DEFAULT_ACCEPTED_STATUS_CODES,
)
Manages cached routes.
Example
from aiocache import SimpleMemoryCache
from fastapi import APIRouter, FastAPI
from fastapi_caching_route import CachingRoute, FastAPICache
router = APIRouter(route_class=CachingRoute)
cache = FastAPICache(SimpleMemoryCache())
@cache()
@router.get('/')
def cached() -> str:
return 'Hello, World!'
app = FastAPI()
app.include_router(router)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
BaseCache
|
aiocache instance to perform caching. |
required |
namespace_policy
|
Literal['concat', 'replace']
|
How to process namespaces passed to the decorator. concat (default)Add to the root (passed to the aiocache instance) namespace. replaceReplace the root namespace. |
'concat'
|
accepted_status_codes
|
Set[int] | Iterable[int]
|
Only cache responses with these HTTP status codes. |
DEFAULT_ACCEPTED_STATUS_CODES
|
__call__
__call__(
*,
key_builder=None,
dependencies=(),
vary_headers=(),
namespace=None,
ttl=None,
)
Decorate caching route.
Marks the endpoint for caching by :class:CachingRoute.
cache = FastAPICache(SimpleMemoryCache())
@cache()
@router.get('/')
def cached() -> str:
...
get_cached
get_cached(cache_key, namespace=None)
set_cached
set_cached(cache_key, value, caching_params)
Set cached response.
Returns:
| Type | Description |
|---|---|
Awaitable[bool]
|
|
invalidate_cached
invalidate_cached(cache_key, namespace=None)
Delete cached response.
Returns:
| Type | Description |
|---|---|
Awaitable[int]
|
Number of deleted keys. |
Returns:
| Type | Description |
|---|---|
Awaitable[int]
|
Number of deleted keys. |
prepare_cache_params
prepare_cache_params(cache_params)
Prepare cache backend parameters for a request.
set_cache_header
set_cache_header(headers, *, hit)
Set a cache status header.