API Reference
Main Cache Interface
fast_cache.FastAPICache
FastAPI Cache Extension.
This class provides caching utilities for FastAPI applications, including decorator-based caching and dependency-injection-based backend access.
Initialize the FastAPICache instance.
Source code in fast_cache/integration.py
get_cache
Get the configured cache backend for dependency injection.
Returns:
Name | Type | Description |
---|---|---|
CacheBackend |
CacheBackend
|
The configured cache backend instance. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If the cache is not initialized. |
Source code in fast_cache/integration.py
cached
Decorator for caching function results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as a timedelta. |
None
|
key_builder
|
Optional[Callable[..., str]]
|
Custom function to build the cache key. |
None
|
namespace
|
Optional[str]
|
Optional namespace for the cache key. |
None
|
Returns:
Name | Type | Description |
---|---|---|
Callable |
Callable[[Callable[..., Any]], Callable[..., Any]]
|
A decorator that caches the function result. |
Source code in fast_cache/integration.py
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 153 154 155 156 157 158 159 160 |
|
lifespan_handler
async
Lifespan context manager for FastAPI.
This can be used as the lifespan
argument to FastAPI to manage
cache lifecycle.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
FastAPI
|
The FastAPI application instance. |
required |
Yields:
Type | Description |
---|---|
AsyncIterator[None]
|
None |
Source code in fast_cache/integration.py
init_app
Initialize the cache extension.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
FastAPI
|
FastAPI application instance. |
required |
backend
|
CacheBackend
|
Cache backend instance. |
required |
default_expire
|
Optional[Union[int, timedelta]]
|
Default expiration time for cached items. |
None
|
Source code in fast_cache/integration.py
Backends
fast_cache.InMemoryBackend
Bases: CacheBackend
Initializes a new instance of the InMemoryBackend cache.
This backend provides an in-memory cache with optional LRU (Least Recently Used) eviction, namespace support, thread and async safety, and automatic periodic cleanup of expired items. It is suitable for single-process, multi-threaded, or asyncio-based applications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
A namespace prefix for all cache keys. This allows multiple independent caches to share the same process. Defaults to "fastapi-cache". |
'fastapi-cache'
|
max_size
|
Optional[int]
|
The maximum number of items to store in the cache. If set, the cache will evict the least recently used items when the limit is exceeded. If None, the cache size is unlimited. Defaults to None. |
None
|
cleanup_interval
|
int
|
The interval, in seconds, at which the background cleanup job runs to remove expired cache entries. Defaults to 30. |
30
|
Notes
- The backend uses an OrderedDict to maintain LRU order.
- Both synchronous (thread-safe) and asynchronous (asyncio-safe) operations are supported.
- Expired items are removed automatically by a background scheduler.
- This backend is not suitable for multi-process or distributed environments.
Initialize the in-memory cache backend.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
namespace
|
str
|
Namespace prefix for all keys. |
'fastapi-cache'
|
max_size
|
Optional[int]
|
Optional maximum number of items (LRU eviction if set). |
None
|
cleanup_interval
|
int
|
Interval in seconds for background cleanup. |
30
|
Source code in fast_cache/backends/memory.py
get
Synchronously retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is deleted from the cache (lazy deletion). Accessing an item moves it to the end of the LRU order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- Thread-safe.
- Expired entries are removed on access.
- Updates LRU order on access.
Source code in fast_cache/backends/memory.py
set
Synchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion. Setting an item moves it to the end of the LRU order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- Thread-safe.
- Triggers LRU eviction if max_size is set.
- Updates LRU order on set.
Source code in fast_cache/backends/memory.py
delete
Synchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Thread-safe.
- The key is automatically namespaced.
Source code in fast_cache/backends/memory.py
clear
Synchronously removes all cache entries in the current namespace.
This method deletes all entries whose keys match the current namespace prefix.
Notes
- Thread-safe.
- Only entries in the current namespace are affected.
- This operation can be expensive if the cache is large.
Source code in fast_cache/backends/memory.py
has
Synchronously checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Thread-safe.
- Expired entries are not considered present and are removed on check.
- Updates LRU order on access.
Source code in fast_cache/backends/memory.py
aget
async
Asynchronously retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is deleted from the cache (lazy deletion). Accessing an item moves it to the end of the LRU order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- Asyncio-safe.
- Expired entries are removed on access.
- Updates LRU order on access.
Source code in fast_cache/backends/memory.py
aset
async
Asynchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion. Setting an item moves it to the end of the LRU order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- Asyncio-safe.
- Triggers LRU eviction if max_size is set.
- Updates LRU order on set.
Source code in fast_cache/backends/memory.py
adelete
async
Asynchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Asyncio-safe.
- The key is automatically namespaced.
Source code in fast_cache/backends/memory.py
aclear
async
Asynchronously removes all cache entries in the current namespace.
This method deletes all entries whose keys match the current namespace prefix.
Notes
- Asyncio-safe.
- Only entries in the current namespace are affected.
- This operation can be expensive if the cache is large.
Source code in fast_cache/backends/memory.py
ahas
async
Asynchronously checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Asyncio-safe.
- Expired entries are not considered present and are removed on check.
- Updates LRU order on access.
Source code in fast_cache/backends/memory.py
close
Closes the backend and stops the background cleanup scheduler.
This method should be called when the backend is no longer needed to ensure all resources are released and background jobs are stopped.
Notes
- After calling this method, the cache is cleared and cannot be used.
- The background cleanup scheduler is stopped.
Source code in fast_cache/backends/memory.py
fast_cache.RedisBackend
Bases: CacheBackend
Redis cache backend implementation with namespace support.
Attributes:
Name | Type | Description |
---|---|---|
_namespace |
str
|
Namespace prefix for all keys. |
_sync_pool |
ConnectionPool
|
Synchronous Redis connection pool. |
_async_pool |
ConnectionPool
|
Asynchronous Redis connection pool. |
_sync_client |
Redis
|
Synchronous Redis client. |
_async_client |
Redis
|
Asynchronous Redis client. |
Initialize Redis backend with connection URL and pool settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
redis_url
|
str
|
Redis connection URL (e.g., "redis://localhost:6379/0"). |
required |
namespace
|
str
|
Namespace prefix for all keys (default: "fastapi-cache"). |
'fastapi-cache'
|
pool_size
|
int
|
Minimum number of connections in the pool. |
10
|
max_connections
|
int
|
Maximum number of connections in the pool. |
20
|
Source code in fast_cache/backends/redis.py
aget
async
Asynchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/redis.py
get
Synchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/redis.py
aset
async
Asynchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/redis.py
set
Synchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/redis.py
adelete
async
Asynchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in fast_cache/backends/redis.py
delete
Synchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
aclear
async
Asynchronously clear all values from the namespace.
clear
Synchronously clear all values from the namespace.
Source code in fast_cache/backends/redis.py
ahas
async
Asynchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Source code in fast_cache/backends/redis.py
has
Synchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Source code in fast_cache/backends/redis.py
close
async
Close Redis connections and clean up pools.
fast_cache.PostgresBackend
PostgresBackend(dsn, namespace='fastapi', min_size=1, max_size=10, cleanup_interval=30, auto_cleanup=True)
Bases: CacheBackend
PostgreSQL cache backend implementation.
Uses an UNLOGGED TABLE for performance and lazy expiration.
Initializes a new instance of the PostgresBackend cache.
This backend uses a PostgreSQL database to store cache entries in an UNLOGGED TABLE for improved performance. It supports both synchronous and asynchronous operations, lazy expiration, and periodic cleanup of expired entries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dsn
|
str
|
The PostgreSQL DSN (Data Source Name) string used to connect to the database. |
required |
namespace
|
str
|
A namespace prefix for all cache keys. This allows multiple independent caches to share the same database table. Only alphanumeric characters and underscores are allowed. Defaults to "fastapi". |
'fastapi'
|
min_size
|
int
|
The minimum number of connections to maintain in the connection pool. Defaults to 1. |
1
|
max_size
|
int
|
The maximum number of connections allowed in the connection pool. Defaults to 10. |
10
|
cleanup_interval
|
int
|
The interval, in seconds, at which the background cleanup job runs to remove expired cache entries. Defaults to 30 seconds. |
30
|
auto_cleanup
|
bool
|
If True, automatically starts the background cleanup scheduler on initialization. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ImportError
|
If the required |
ValueError
|
If the provided namespace contains invalid characters. |
Notes
- The backend creates the cache table and an index on the expiration column if they do not already exist.
- The cleanup scheduler can be started or stopped manually.
- Both synchronous and asynchronous connection pools are managed.
Source code in fast_cache/backends/postgres.py
set
Stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object/values to cache. It will be serialized using pickle. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- The key is automatically namespaced.
- Expired entries are lazily deleted on access or by the cleanup job.
Source code in fast_cache/backends/postgres.py
get
Retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is deleted from the cache (lazy deletion).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- The value is deserialized using pickle.
- Expired entries are removed on access.
Source code in fast_cache/backends/postgres.py
delete
Deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- The key is automatically namespaced.
Source code in fast_cache/backends/postgres.py
has
Checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Expired entries are not considered present.
- Does not remove expired entries; use
get
for lazy deletion.
Source code in fast_cache/backends/postgres.py
clear
Removes all cache entries in the current namespace.
This method deletes all rows from the cache table whose keys match the current namespace prefix.
Notes
- Only entries in the current namespace are affected.
- This operation can be expensive if the cache is large.
Source code in fast_cache/backends/postgres.py
aset
async
Asynchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object/values to cache. It will be serialized using pickle. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- Uses the asynchronous connection pool.
- The key is automatically namespaced.
Source code in fast_cache/backends/postgres.py
aget
async
Asynchronously retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is deleted from the cache (lazy deletion).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- Uses the asynchronous connection pool.
- The value is deserialized using pickle.
- Expired entries are removed on access.
Source code in fast_cache/backends/postgres.py
adelete
async
Asynchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Uses the asynchronous connection pool.
- The key is automatically namespaced.
Source code in fast_cache/backends/postgres.py
ahas
async
Asynchronously checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Uses the asynchronous connection pool.
- Expired entries are not considered present.
- Does not remove expired entries; use
aget
for lazy deletion.
Source code in fast_cache/backends/postgres.py
aclear
async
Asynchronously removes all cache entries in the current namespace.
This method deletes all rows from the cache table whose keys match the current namespace prefix.
Notes
- Uses the asynchronous connection pool.
- Only entries in the current namespace are affected.
- This operation can be expensive if the cache is large.
Source code in fast_cache/backends/postgres.py
aclose
async
Asynchronously closes the connection pools and stops the cleanup scheduler.
This method should be called when the backend is no longer needed to ensure all resources are released and background jobs are stopped.
Notes
- Closes both synchronous and asynchronous connection pools.
- Stops the background cleanup scheduler.
Source code in fast_cache/backends/postgres.py
close
Closes the synchronous connection pool and stops the cleanup scheduler.
This method should be called when the backend is no longer needed to ensure all resources are released and background jobs are stopped.
Notes
- Only closes the synchronous connection pool.
- Stops the background cleanup scheduler.
Source code in fast_cache/backends/postgres.py
fast_cache.MemcachedBackend
Bases: CacheBackend
Initializes a new instance of the MemcachedBackend cache.
This backend provides a cache using Memcached as the storage layer. It supports both synchronous and asynchronous operations, and uses a namespace prefix for all keys to avoid collisions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
host
|
str
|
The hostname or IP address of the Memcached server. |
required |
port
|
int
|
The port number of the Memcached server. |
required |
pool_size
|
int
|
The maximum number of connections in the async pool. Defaults to 10. |
10
|
pool_minsize
|
int
|
The minimum number of connections in the async pool. Defaults to 1. |
1
|
namespace
|
str
|
Prefix for all cache keys. Defaults to "fastapi_cache". |
'fastapi_cache'
|
Raises:
Type | Description |
---|---|
ImportError
|
If the required |
Notes
- Both synchronous and asynchronous Memcached clients are initialized.
- The async client is created per event loop.
- All cache keys are automatically namespaced.
Source code in fast_cache/backends/memcached.py
get
Synchronously retrieves a value from the cache by key.
If the key does not exist, returns None.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found. |
Notes
- The value is deserialized using pickle.
- Handles deserialization errors gracefully.
- Thread-safe for Memcached client.
Source code in fast_cache/backends/memcached.py
set
Synchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- The value is serialized using pickle.
- Thread-safe for Memcached client.
- Expiration is handled by Memcached.
Source code in fast_cache/backends/memcached.py
delete
Synchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Thread-safe for Memcached client.
- The key is automatically namespaced.
Source code in fast_cache/backends/memcached.py
clear
Synchronously removes all cache entries from Memcached.
Memcached does not support namespace-based clearing, so this operation flushes the entire cache, removing all entries regardless of namespace.
Notes
- Thread-safe for Memcached client.
- This operation affects all keys in the Memcached instance.
- Use with caution in shared environments.
Source code in fast_cache/backends/memcached.py
has
Synchronously checks if a cache key exists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Notes
- Thread-safe for Memcached client.
- Expired entries are not considered present.
Source code in fast_cache/backends/memcached.py
aget
async
Asynchronously retrieves a value from the cache by key.
If the key does not exist, returns None.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found. |
Notes
- The value is deserialized using pickle.
- Handles deserialization errors gracefully.
- Asyncio-safe for Memcached client.
Source code in fast_cache/backends/memcached.py
aset
async
Asynchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- The value is serialized using pickle.
- Asyncio-safe for Memcached client.
- Expiration is handled by Memcached.
Source code in fast_cache/backends/memcached.py
adelete
async
Asynchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Asyncio-safe for Memcached client.
- The key is automatically namespaced.
Source code in fast_cache/backends/memcached.py
aclear
async
Asynchronously removes all cache entries from Memcached.
Memcached does not support namespace-based clearing, so this operation flushes the entire cache, removing all entries regardless of namespace.
Notes
- Asyncio-safe for Memcached client.
- This operation affects all keys in the Memcached instance.
- Use with caution in shared environments.
Source code in fast_cache/backends/memcached.py
ahas
async
Asynchronously checks if a cache key exists.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Notes
- Asyncio-safe for Memcached client.
- Expired entries are not considered present.
Source code in fast_cache/backends/memcached.py
close
async
Asynchronously closes both the async and sync Memcached clients.
This method should be called when the backend is no longer needed to ensure all resources are released.
Notes
- After calling this method, the backend cannot be used.
- Closes both the async and sync clients.
Source code in fast_cache/backends/memcached.py
fast_cache.MongoDBBackend
Bases: CacheBackend
MongoDB cache backend with both sync and async support. Uses a TTL index for automatic expiration of cache entries.
Each cache entry is stored as a document with
- _id: the cache key (optionally namespaced)
- value: the pickled cached value
- expires_at: epoch time when the entry should expire
Expired documents are deleted automatically by MongoDB's TTL monitor, but expiration is also checked in code to avoid returning stale data.
Initialize the MongoDB backend.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
uri
|
str
|
MongoDB connection URI (should include the database name). |
required |
namespace
|
Optional[str]
|
Optional prefix for all cache keys and the collection name. Defaults to "fastapi_cache". |
'fastapi_cache'
|
Raises: ImportError: If pymongo is not installed.
Source code in fast_cache/backends/mongodb.py
get
Synchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found or expired. |
Source code in fast_cache/backends/mongodb.py
set
Synchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
value
|
Any
|
The value to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. If None, the entry never expires. |
None
|
Source code in fast_cache/backends/mongodb.py
delete
Synchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
clear
has
Synchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Source code in fast_cache/backends/mongodb.py
aget
async
Asynchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found or expired. |
Source code in fast_cache/backends/mongodb.py
aset
async
Asynchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
value
|
Any
|
The value to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. If None, the entry never expires. |
None
|
Source code in fast_cache/backends/mongodb.py
adelete
async
Asynchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
aclear
async
Asynchronously clear all values from the namespace.
ahas
async
Asynchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Source code in fast_cache/backends/mongodb.py
close
fast_cache.FirestoreBackend
FirestoreBackend(credential_path=None, namespace='fastapi_cache', collection_name='cache_entries', cleanup_interval=30, auto_cleanup=True)
Bases: CacheBackend
Initializes a new instance of the FirestoreBackend cache.
This backend provides a cache using Google Cloud Firestore as the storage layer. It supports both synchronous and asynchronous operations, manual expiration management, and optional periodic cleanup of expired entries.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
credential_path
|
Optional[str]
|
Path to the Firebase Admin SDK credentials file. If None, uses the GOOGLE_APPLICATION_CREDENTIALS environment variable. Defaults to None. |
None
|
namespace
|
Optional[str]
|
Optional prefix for all cache keys. Defaults to "fastapi_cache". |
'fastapi_cache'
|
collection_name
|
Optional[str]
|
Name of the Firestore collection to use for storing cache entries. Defaults to "cache_entries". |
'cache_entries'
|
cleanup_interval
|
int
|
Interval in seconds for periodic cleanup of expired entries. Defaults to 30. |
30
|
auto_cleanup
|
bool
|
Whether to automatically start the cleanup scheduler on initialization. Defaults to True. |
True
|
Raises:
Type | Description |
---|---|
ImportError
|
If the required |
Notes
- The backend uses a hashed, namespaced key for each Firestore document.
- Expired entries are managed via a custom
expires_at
field. - Both synchronous and asynchronous Firestore clients are initialized.
- The cleanup scheduler can be started or stopped manually.
Source code in fast_cache/backends/google_firestore.py
get
Synchronously retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is not automatically deleted.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- The value is deserialized using pickle.
- Handles deserialization errors gracefully.
- Thread-safe for Firestore client.
Source code in fast_cache/backends/google_firestore.py
set
Synchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- The value is serialized using pickle.
- Thread-safe for Firestore client.
Source code in fast_cache/backends/google_firestore.py
delete
Synchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Thread-safe for Firestore client.
- The key is automatically namespaced and hashed.
Source code in fast_cache/backends/google_firestore.py
clear
Synchronously removes all cache entries in the collection.
This method deletes all documents in the configured Firestore collection. Note that Firestore does not support direct namespace-based clearing, so all entries in the collection are removed.
Notes
- Thread-safe for Firestore client.
- This operation can be expensive if the collection is large.
- For more granular clearing, consider adding a namespace field to documents.
Source code in fast_cache/backends/google_firestore.py
has
Synchronously checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Thread-safe for Firestore client.
- Expired entries are not considered present.
Source code in fast_cache/backends/google_firestore.py
aget
async
Asynchronously retrieves a value from the cache by key.
If the key does not exist or the entry has expired, returns None. If the entry is expired, it is not automatically deleted.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached Python object, or None if not found or expired. |
Notes
- The value is deserialized using pickle.
- Handles deserialization errors gracefully.
- Asyncio-safe for Firestore client.
Source code in fast_cache/backends/google_firestore.py
aset
async
Asynchronously stores a value in the cache under the specified key.
If the key already exists, its value and expiration time are updated. Optionally, an expiration time can be set, after which the entry will be considered expired and eligible for deletion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to store the value under. |
required |
value
|
Any
|
The Python object to cache. |
required |
expire
|
Optional[Union[int, timedelta]]
|
The expiration time for the cache entry. Can be specified as an integer (seconds) or a timedelta. If None, the entry does not expire. |
None
|
Notes
- The value is serialized using pickle.
- Asyncio-safe for Firestore client.
Source code in fast_cache/backends/google_firestore.py
adelete
async
Asynchronously deletes a cache entry by key.
If the key does not exist, this method does nothing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to delete. |
required |
Notes
- Asyncio-safe for Firestore client.
- The key is automatically namespaced and hashed.
Source code in fast_cache/backends/google_firestore.py
aclear
async
Asynchronously removes all cache entries in the collection.
This method deletes all documents in the configured Firestore collection. Note that Firestore does not support direct namespace-based clearing, so all entries in the collection are removed.
Notes
- Asyncio-safe for Firestore client.
- This operation can be expensive if the collection is large.
- For more granular clearing, consider adding a namespace field to documents.
Source code in fast_cache/backends/google_firestore.py
ahas
async
Asynchronously checks if a cache key exists and is not expired.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The cache key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists and is not expired, False otherwise. |
Notes
- Asyncio-safe for Firestore client.
- Expired entries are not considered present.
Source code in fast_cache/backends/google_firestore.py
close
Closes the synchronous Firestore client and stops the cleanup scheduler.
This method should be called when the backend is no longer needed to ensure all resources are released and background jobs are stopped.
Notes
- After calling this method, the synchronous client is closed and cannot be used.
- The background cleanup scheduler is stopped.
Source code in fast_cache/backends/google_firestore.py
aclose
async
Closes the asynchronous Firestore client and stops the cleanup scheduler.
This method should be called when the backend is no longer needed to ensure all resources are released and background jobs are stopped.
Notes
- After calling this method, the asynchronous client is closed and cannot be used.
- The background cleanup scheduler is stopped.
Source code in fast_cache/backends/google_firestore.py
fast_cache.DynamoDBBackend
DynamoDBBackend(table_name, region_name, namespace='cache', aws_access_key_id=None, aws_secret_access_key=None, endpoint_url=None, create_table=True)
Bases: CacheBackend
DynamoDB cache backend implementation with namespace support.
Attributes:
Name | Type | Description |
---|---|---|
_namespace |
str
|
Namespace prefix for all keys. |
_table_name |
str
|
DynamoDB table name. |
_sync_client |
client
|
Synchronous DynamoDB client. |
_async_client |
client
|
Asynchronous DynamoDB client. |
_sync_resource |
resource
|
Synchronous DynamoDB resource. |
_async_resource |
resource
|
Asynchronous DynamoDB resource. |
Initialize DynamoDB backend with table and connection settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
table_name
|
str
|
DynamoDB table name for cache storage. |
required |
namespace
|
str
|
Namespace prefix for all keys (default: "fastapi-cache"). |
'cache'
|
region_name
|
str
|
AWS region name (default: "us-east-1"). |
required |
aws_access_key_id
|
Optional[str]
|
AWS access key ID. |
None
|
aws_secret_access_key
|
Optional[str]
|
AWS secret access key. |
None
|
endpoint_url
|
Optional[str]
|
Custom endpoint URL (for local DynamoDB). |
None
|
create_table
|
bool
|
Whether to create table if it doesn't exist. |
True
|
Source code in fast_cache/backends/dynamodb.py
get
Synchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/dynamodb.py
aget
async
Asynchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/dynamodb.py
set
Synchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/dynamodb.py
aset
async
Asynchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/dynamodb.py
delete
Synchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in fast_cache/backends/dynamodb.py
adelete
async
Asynchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
Source code in fast_cache/backends/dynamodb.py
has
Synchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Source code in fast_cache/backends/dynamodb.py
ahas
async
Asynchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Source code in fast_cache/backends/dynamodb.py
clear
Synchronously clear all values from the namespace.
Source code in fast_cache/backends/dynamodb.py
aclear
async
Asynchronously clear all values from the namespace.
Source code in fast_cache/backends/dynamodb.py
close
async
Close DynamoDB connections and clean up resources.
Source code in fast_cache/backends/dynamodb.py
Backend Base Class
fast_cache.backends.backend.CacheBackend
Bases: ABC
Abstract base class for cache backends.
All cache backend implementations must inherit from this class and implement both synchronous and asynchronous methods for cache operations.
aget
abstractmethod
async
Asynchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/backend.py
get
abstractmethod
Synchronously retrieve a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to retrieve. |
required |
Returns:
Type | Description |
---|---|
Optional[Any]
|
Optional[Any]: The cached value, or None if not found. |
Source code in fast_cache/backends/backend.py
aset
abstractmethod
async
Asynchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/backend.py
set
abstractmethod
Synchronously set a value in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key under which to store the value. |
required |
value
|
Any
|
The value to store. |
required |
expire
|
Optional[Union[int, timedelta]]
|
Expiration time in seconds or as timedelta. |
None
|
Source code in fast_cache/backends/backend.py
adelete
abstractmethod
async
Asynchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
delete
abstractmethod
Synchronously delete a value from the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to delete. |
required |
aclear
abstractmethod
async
clear
abstractmethod
ahas
abstractmethod
async
Asynchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |
Source code in fast_cache/backends/backend.py
has
abstractmethod
Synchronously check if a key exists in the cache.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key
|
str
|
The key to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the key exists, False otherwise. |