### Setup FastAPI Cachekit for Development and Testing Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Instructions for setting up the FastAPI Cachekit project for development, including installing test and development dependencies using uv or poetry. ```bash uv sync --all-group ``` ```bash poetry install --with dev ``` -------------------------------- ### Install FastAPI Cachekit with All Backends Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for all available backends at once using pip, uv, or poetry. ```bash pip install fastapi-cachekit[all] ``` ```bash uv add fastapi-cachekit[all] ``` ```bash poetry add fastapi-cachekit -E all ``` -------------------------------- ### Install FastAPI Cachekit with MongoDB Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the MongoDB backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[mongodb] ``` ```bash uv add fastapi-cachekit[mongodb] ``` ```bash poetry add fastapi-cachekit -E mongodb ``` -------------------------------- ### Install FastAPI Cachekit with Postgres Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the Postgres backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[postgres] ``` ```bash uv add fastapi-cachekit[postgres] ``` ```bash poetry add fastapi-cachekit -E postgres ``` -------------------------------- ### Install FastAPI Cachekit with Memcached Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the Memcached backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[memcached] ``` ```bash uv add fastapi-cachekit[memcached] ``` ```bash poetry add fastapi-cachekit -E memcached ``` -------------------------------- ### Install FastAPI Cachekit with Redis Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the Redis backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[redis] ``` ```bash uv add fastapi-cachekit[redis] ``` ```bash poetry add fastapi-cachekit -E redis ``` -------------------------------- ### Install FastAPI Cachekit with Firestore Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the Firestore backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[firestore] ``` ```bash uv add fastapi-cachekit[firestore] ``` ```bash poetry add fastapi-cachekit -E firestore ``` -------------------------------- ### Install FastAPI Cachekit with DynamoDB Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Commands to install FastAPI Cachekit with support for the DynamoDB backend using pip, uv, or poetry. ```bash pip install fastapi-cachekit[dynamodb] ``` ```bash uv add fastapi-cachekit[dynamodb] ``` ```bash poetry add fastapi-cachekit -E dynamodb ``` -------------------------------- ### Install FastAPI Cachekit Core Package (In-Memory) Source: https://github.com/devbijay/fast-cache/blob/main/docs/installation.md Instructions for installing the core FastAPI Cachekit package, which includes only the in-memory backend, using pip, uv, or poetry. ```bash pip install fastapi-cachekit ``` ```bash uv add fastapi-cachekit ``` ```bash poetry add fastapi-cachekit ``` -------------------------------- ### FastAPI application with Redis caching quick start Source: https://github.com/devbijay/fast-cache/blob/main/README.md A comprehensive quick start example for integrating `fastapi-cachekit` into a FastAPI application. It demonstrates initializing the cache with a Redis backend, using the `@cache.cached` decorator for automatic function result caching, and manually interacting with the cache backend through FastAPI's dependency injection system. ```python from fastapi import FastAPI, Depends from fast_cache import cache, RedisBackend from typing import Annotated app = FastAPI() # Initialize cache with Redis backend cache.init_app( app=app, backend=RedisBackend(redis_url="redis://localhost:6379/0", namespace="myapp"), default_expire=300 # 5 minutes default expiration ) # Use function caching decorator @app.get("/items/{item_id}") @cache.cached(expire=60) # Cache for 60 seconds async def read_item(item_id: int): # Expensive operation simulation return {"item_id": item_id, "name": f"Item {item_id}"} # Use cache backend directly with dependency injection @app.get("/manual-cache") async def manual_cache_example(cache_backend: Annotated[RedisBackend, Depends(cache.get_cache)]): # Check if key exists has_key = await cache_backend.ahas("my-key") if not has_key: # Set a value in the cache await cache_backend.aset("my-key", {"data": "cached value"}, expire=30) return {"cache_set": True} # Get the value from cache value = await cache_backend.aget("my-key") return {"cached_value": value} ``` -------------------------------- ### Install fastapi-cachekit with various backend options Source: https://github.com/devbijay/fast-cache/blob/main/README.md Commands to install the `fastapi-cachekit` library. This includes the base package for in-memory caching, and optional installations for specific backends like Redis, PostgreSQL, Memcached, MongoDB, Firestore, and DynamoDB, or all backends at once. ```bash pip install fastapi-cachekit ``` ```bash pip install fastapi-cachekit[redis] ``` ```bash pip install fastapi-cachekit[postgres] ``` ```bash pip install fastapi-cachekit[memcached] ``` ```bash pip install fastapi-cachekit[mongodb] ``` ```bash pip install fastapi-cachekit[firestore] ``` ```bash pip install fastapi-cachekit[dynamodb] ``` ```bash pip install fastapi-cachekit[all] ``` -------------------------------- ### Install FastAPI Cachekit Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/in_memory.md Command to install the `fastapi-cachekit` library, which includes the in-memory backend. No extra dependencies are required for the in-memory backend. ```bash pip install fastapi-cachekit ``` -------------------------------- ### Install FastAPI Cachekit with DynamoDB Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Provides instructions on how to install the `fastapi-cachekit` library with DynamoDB support using pip, ensuring all necessary dependencies are included for DynamoDB integration. ```bash pip install fastapi-cachekit[dynamodb] ``` -------------------------------- ### Install FastAPI Cachekit with Postgres Support Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/postgres.md Instructions for installing the FastAPI Cachekit library with PostgreSQL backend support using various Python package managers like pip, uv, and poetry. ```Shell pip install fastapi-cachekit[postgres] ``` ```Shell uv add fastapi-cachekit[postgres] ``` ```Shell poetry add fastapi-cachekit -E postgres ``` -------------------------------- ### Install fastapi-cachekit with Firestore Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/firestore.md Instructions on how to install the fastapi-cachekit library along with its Firestore-specific dependencies using pip, enabling Firestore as a caching backend. ```bash pip install fastapi-cachekit[firestore] ``` -------------------------------- ### Install FastAPI Cachekit with Memcached Support Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Commands to install FastAPI Cachekit with Memcached backend dependencies using pip, uv, or poetry. ```bash pip install fastapi-cachekit[memcached] ``` ```bash uv add fastapi-cachekit[memcached] ``` ```bash poetry add fastapi-cachekit -E memcached ``` -------------------------------- ### MemcachedBackend Basic Setup Parameters Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Describes the host, port, and namespace parameters used in the basic initialization of MemcachedBackend. ```APIDOC MemcachedBackend Parameters (Basic Setup): host: Memcached server host (default: "localhost") port: Memcached server port (default: 11211) namespace: Prefix for all cache keys (default: "fastapi-cache") ``` -------------------------------- ### Install FastAPI Cachekit with MongoDB Support Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/mongodb.md Instructions for installing the FastAPI Cachekit library with MongoDB backend dependencies using various Python package managers like pip, uv, and poetry. ```bash pip install fastapi-cachekit[mongodb] ``` ```bash uv add fastapi-cachekit[mongodb] ``` ```bash poetry add fastapi-cachekit -E mongodb ``` -------------------------------- ### Install Redis Backend for FastAPI Cachekit Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/redis.md Installs the `fastapi-cachekit` library with the Redis backend dependency using pip. This command ensures all necessary components for Redis integration are available. ```bash pip install fastapi-cachekit[redis] ``` -------------------------------- ### Cache FastAPI Endpoint Responses with Decorator in Python Source: https://github.com/devbijay/fast-cache/blob/main/docs/usage.md Illustrates applying the @cache.cached() decorator directly to a FastAPI endpoint to cache its HTTP responses. The example caches the '/expensive' GET route's response for 120 seconds, suitable for both synchronous and asynchronous endpoints. ```python from fastapi import FastAPI from fast_cache import FastAPICache, InMemoryBackend app = FastAPI() cache = FastAPICache() backend = InMemoryBackend() cache.init_app(app, backend) @app.get("/expensive") @cache.cached(expire=120) async def expensive_route(x: int): # This endpoint's response will be cached for 2 minutes return {"result": x * 2} ``` -------------------------------- ### Implement a Custom Cache Backend Source: https://github.com/devbijay/fast-cache/blob/main/README.md Shows the basic structure for creating a custom cache backend by inheriting from `fast_cache.backends.backend.CacheBackend`. This requires implementing all abstract methods, including both synchronous and asynchronous versions of `get`, `set`, and other core caching operations. ```python from fast_cache.backends.backend import CacheBackend from typing import Any, Optional, Union from datetime import timedelta class MyCustomBackend(CacheBackend): # Implement all required methods async def aget(self, key: str) -> Any: # Your implementation here ... def get(self, key: str) -> Any: # Your implementation here ... # ... implement all other required methods ``` -------------------------------- ### Initialize fastapi-cachekit with a Redis backend Source: https://github.com/devbijay/fast-cache/blob/main/README.md Detailed example of initializing the `fastapi-cachekit` with a `RedisBackend`. This snippet shows how to configure the Redis URL, namespace, maximum connections, and set a default expiration time using `datetime.timedelta`. ```python from fastapi import FastAPI from fast_cache import cache, RedisBackend from datetime import timedelta app = FastAPI() cache.init_app( app=app, backend=RedisBackend( redis_url="redis://localhost:6379/0", namespace="myapp", max_connections=20 ), default_expire=timedelta(minutes=5) ) ``` -------------------------------- ### Start Local DynamoDB Instance using Docker Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Provides a convenient bash command to run a local DynamoDB instance in a Docker container. This is highly recommended for development and testing purposes, allowing work without live AWS services. ```bash docker run -p 8000:8000 amazon/dynamodb-local ``` -------------------------------- ### Perform Direct Operations on DynamoDB Cache Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Provides examples of directly interacting with the `DynamoDBBackend` instance for fine-grained control over cache entries. It shows how to asynchronously set, get, check existence, delete, and clear cache entries. ```python # Set a value await backend.aset("mykey", {"foo": "bar"}, expire=30) # Get a value value = await backend.aget("mykey") # Check if a key exists exists = await backend.ahas("mykey") # Delete a key await backend.adelete("mykey") # Clear all cache in the namespace await backend.aclear() ``` -------------------------------- ### Cache Function Results with Decorator in Python Source: https://github.com/devbijay/fast-cache/blob/main/docs/usage.md Demonstrates how to use the @cache.cached() decorator to cache the return value of any synchronous or asynchronous Python function. The example shows caching an 'expensive_computation' function for 60 seconds using an in-memory backend. ```python from fast_cache import FastAPICache, InMemoryBackend cache = FastAPICache() backend = InMemoryBackend() cache.init_app(app, backend) @cache.cached(expire=60) def expensive_computation(x: int): # This result will be cached for 60 seconds return x * 2 result = expensive_computation(10) # Cached! ``` -------------------------------- ### Initialize MongoDB Backend in FastAPI Application Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/mongodb.md Demonstrates how to initialize the MongoDBBackend for FastAPI Cachekit, connecting to a MongoDB instance using a URI and specifying a namespace for cache keys. This setup integrates the cache backend with the FastAPI application, enabling persistent caching. ```python from fast_cache import cache, MongoDBBackend backend = MongoDBBackend( uri="mongodb://user:password@localhost:27017/mydb", namespace="myapp_cache" ) cache.init_app(app, backend) ``` -------------------------------- ### Advanced Caching in FastAPI using Dependency Injection in Python Source: https://github.com/devbijay/fast-cache/blob/main/docs/usage.md Shows how to inject the cache backend using Depends(cache.get_cache) in a FastAPI route for more granular control over caching. This allows for custom cache keys, manual aget/aset operations, and conditional caching logic, demonstrated by caching user profiles. ```python from fastapi import Depends from fast_cache import cache, CacheBackend ## Add The cache init Here @app.get("/profile/{user_id}") async def get_profile( user_id: int, cache_backend: CacheBackend = Depends(cache.get_cache) ): key = f"profile:{user_id}" cached = await cache_backend.aget(key) if cached: return {"profile": cached, "cached": True} # Simulate expensive fetch profile = {"user_id": user_id, "bio": f"User {user_id} bio"} await cache_backend.aset(key, profile, expire=60) return {"profile": profile, "cached": False} ``` -------------------------------- ### Cache FastAPI Endpoint with @cache.cached Decorator Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/firestore.md An example demonstrating how to apply caching to a FastAPI GET endpoint using the @cache.cached decorator. The 'expire' parameter specifies the cache duration in seconds, effectively caching the response of the 'expensive_operation' function. ```python @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): return {"result": x * 2} ``` -------------------------------- ### Cache function results using the @cache.cached decorator Source: https://github.com/devbijay/fast-cache/blob/main/README.md Illustrates various ways to use the `@cache.cached` decorator for caching function results. Examples include caching with default expiration, custom expiration and namespace for asynchronous functions, custom key generation using a lambda, and a mechanism to bypass the cache for specific function calls. ```python from fast_cache import cache # Cache with default expiration time @cache.cached() def get_user_data(user_id: int): # Expensive database query return {"user_id": user_id, "name": "John Doe"} # Cache with custom namespace and expiration @cache.cached(namespace="users", expire=300) async def get_user_profile(user_id: int): # Async expensive operation return {"user_id": user_id, "profile": "..."} # Cache with custom key builder @cache.cached(key_builder=lambda user_id, **kwargs: f"user:{user_id}") def get_user_permissions(user_id: int): # Complex permission calculation return ["read", "write"] # Skip Cache for Specific Calls Sometimes you need to bypass the cache for certain requests: @cache.cached() async def get_weather(city: str, skip_cache: bool = False): # Function will be called directly if skip_cache is True return await fetch_weather_data(city) ``` -------------------------------- ### Cache FastAPI Endpoint with Decorator Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Illustrates caching a FastAPI endpoint's response using the `@cache.cached` decorator. This example shows how to apply the decorator to an asynchronous function to automatically cache its return value for a specified duration. ```python from fastapi import FastAPI from fast_cache import cache, DynamoDBBackend app = FastAPI() backend = DynamoDBBackend( table_name="my_cache_table", region_name="us-east-1", endpoint_url="http://localhost:8000", aws_access_key_id="fake", aws_secret_access_key="fake", create_table=True, ) cache.init_app(app, backend) @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): # This result will be cached for 60 seconds return {"result": x * 2} ``` -------------------------------- ### Cache FastAPI Endpoint with Redis Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/redis.md Shows how to apply caching to a FastAPI GET endpoint using the `@cache.cached` decorator. The `expire` parameter sets the cache duration in seconds, ensuring the function's result is cached for subsequent requests within that period. ```python @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): return {"result": x * 2} ``` -------------------------------- ### Initialize FastAPI Cachekit with PostgresBackend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/postgres.md Demonstrates how to initialize the FastAPI Cachekit application with the PostgresBackend, specifying the PostgreSQL connection DSN and an optional namespace for cache keys. ```Python from fast_cache import cache, PostgresBackend backend = PostgresBackend( dsn="postgresql://user:password@localhost:5432/mydb", namespace="myapp_cache" ) cache.init_app(app, backend) ``` -------------------------------- ### fast-cache Global Instance API Reference Source: https://github.com/devbijay/fast-cache/blob/main/README.md Documents the key methods available on the global `cache` instance provided by the fast-cache library. This includes methods for initializing the cache with a FastAPI application, retrieving the cache backend for dependency injection, and applying the caching decorator to functions. ```APIDOC cache.init_app(app, backend, default_expire=None) cache.get_cache() cache.cached(expire=None, key_builder=None, namespace=None) ``` -------------------------------- ### Initialize FastAPI Cache with Redis Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/redis.md Demonstrates how to import `FastAPICache` and `RedisBackend`, create instances, and initialize the cache with a FastAPI application using a specified Redis connection string. This sets up the caching mechanism for the application. ```python from fast_cache import FastAPICache, RedisBackend cache = FastAPICache() backend = RedisBackend(redis_url="redis://localhost:6379/0") cache.init_app(app, backend) ``` -------------------------------- ### Initialize Firestore Backend in FastAPI Application Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/firestore.md This snippet demonstrates how to import the necessary classes, instantiate the FirestoreBackend, and initialize the cache application. It highlights optional parameters for credential path, namespace, and collection name for flexible configuration. ```python from fast_cache import cache, FirestoreBackend backend = FirestoreBackend( credential_path="path/to/your/service-account.json", # Optional if using GOOGLE_APPLICATION_CREDENTIALS namespace="my-namespace", # Optional collection_name="cache_entries" # Optional ) cache.init_app(app, backend) ``` -------------------------------- ### Configure PostgresBackend Connection Pool Options Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/postgres.md Shows how to configure advanced options for the PostgresBackend, including connection pool min_size and max_size, in addition to the DSN and namespace. ```Python backend = PostgresBackend( dsn="postgresql://user:password@localhost:5432/mydb", namespace="myapp-cache", min_size=2, max_size=20 ) ``` -------------------------------- ### Configure DynamoDB Backend for Local DynamoDB Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Shows how to initialize the `DynamoDBBackend` to connect to a locally running DynamoDB instance. This configuration involves setting the `endpoint_url` and using dummy AWS credentials, which are sufficient for local testing. ```python backend = DynamoDBBackend( table_name="my_cache_table", region_name="us-east-1", endpoint_url="http://localhost:8000", aws_access_key_id="fake", # Use dummy values for local aws_secret_access_key="fake", # Use dummy values for local create_table=True, ) ``` -------------------------------- ### FirestoreBackend Configuration Options Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/firestore.md Detailed documentation for the configuration parameters available when initializing the FirestoreBackend. It outlines the purpose, type, and default values for each option, such as credential path, namespace, and collection name. ```APIDOC FirestoreBackend: __init__( credential_path: str = None, namespace: str = "fastapi_cache", collection_name: str = "cache_entries" ) credential_path: Path to your Google Cloud service account JSON file. If not provided, uses the GOOGLE_APPLICATION_CREDENTIALS environment variable. namespace: Key prefix for all cache entries (default: "fastapi_cache"). collection_name: Firestore collection to use for cache entries (default: "cache_entries"). ``` -------------------------------- ### Initialize FastAPI Cache with DynamoDB Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Demonstrates how to set up `FastAPICache` using `DynamoDBBackend`, configuring essential parameters such as table name, AWS region, optional namespace, AWS credentials, and endpoint URL. It also shows how to enable automatic table creation. ```python from fast_cache import FastAPICache from fast_cache.dynamodb import DynamoDBBackend cache = FastAPICache() backend = DynamoDBBackend( table_name="my_cache_table", region_name="us-east-1", namespace="my-namespace", # Optional, default: "cache" aws_access_key_id="YOUR_AWS_ACCESS_KEY_ID", # Optional for local aws_secret_access_key="YOUR_AWS_SECRET_ACCESS_KEY", # Optional for local endpoint_url="http://localhost:8000", # For DynamoDB Local create_table=True # Auto-create table if needed ) cache.init_app(app, backend) ``` -------------------------------- ### RedisBackend Configuration Options Source: https://github.com/devbijay/fast-cache/blob/main/README.md Lists the specific configuration parameters available for the Redis cache backend in fast-cache. These options allow users to specify the Redis connection string, define a key namespace, and control the connection pool size for optimal performance. ```APIDOC redis_url namespace pool_size max_connections ``` -------------------------------- ### PostgresBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Provides API documentation for the PostgreSQL cache backend, allowing caching data within a PostgreSQL database. ```APIDOC ::: fast_cache.PostgresBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### MemcachedBackend Full Configuration Options Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Comprehensive list of all configurable parameters for the MemcachedBackend, detailing their purpose and default values. ```APIDOC MemcachedBackend Options: host: Memcached server host (default: "localhost") port: Memcached server port (default: 11211) namespace: String prefix for all cache keys (default: "fastapi-cache") pool_size: Maximum number of connections in the sync pool (default: 2) ``` -------------------------------- ### Initialize MemcachedBackend in FastAPI Application Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Demonstrates how to import and initialize the MemcachedBackend with a FastAPI application, configuring basic connection parameters. ```python from fast_cache import cache, MemcachedBackend backend = MemcachedBackend( host="localhost", port=11211, namespace="myapp-cache" ) cache.init_app(app, backend) ``` -------------------------------- ### InMemoryBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Provides API documentation for the in-memory cache backend, suitable for simple, non-persistent caching within a single application instance. ```APIDOC ::: fast_cache.InMemoryBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### RedisBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Documents the Redis cache backend, enabling distributed and persistent caching using a Redis server. ```APIDOC ::: fast_cache.RedisBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### CacheBackend Base Class API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Documents the abstract base class for all cache backends in the fast-cache library, defining the common interface and methods that all backend implementations must adhere to. ```APIDOC ::: fast_cache.backends.backend.CacheBackend ``` -------------------------------- ### MemcachedBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Documents the Memcached cache backend, offering a high-performance distributed memory object caching system. ```APIDOC ::: fast_cache.MemcachedBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### Configure MemcachedBackend with SASL Authentication Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Shows how to initialize MemcachedBackend with username and password for SASL authentication, if enabled on the Memcached server. ```python backend = MemcachedBackend( host="localhost", port=11211, username="myuser", password="mypassword" ) ``` -------------------------------- ### DynamoDBBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Provides API documentation for the DynamoDB cache backend, leveraging AWS DynamoDB for a fully managed NoSQL database cache. ```APIDOC ::: fast_cache.DynamoDBBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### CacheBackend Interface Methods Reference Source: https://github.com/devbijay/fast-cache/blob/main/README.md Defines the core methods that all cache backends must implement in fast-cache. This interface ensures consistency across different backend implementations, providing both synchronous and asynchronous versions for common caching operations like retrieving, storing, deleting, clearing, and checking key existence. ```APIDOC get(key) / aget(key) set(key, value, expire) / aset(key, value, expire) delete(key) / adelete(key) clear() / aclear() has(key) / ahas(key) ``` -------------------------------- ### Configure InMemoryBackend with Max Size Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/in_memory.md Illustrates how to configure the `InMemoryBackend` with optional parameters like `namespace` and `max_size`. Setting `max_size` enables a Least Recently Used (LRU) eviction policy when the cache reaches its item limit. ```python backend = InMemoryBackend(namespace="myapp-cache", max_size=1000) ``` -------------------------------- ### FastAPICache Main Interface API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Documents the primary caching interface for the fast-cache library, providing core functionalities for cache management and interaction. ```APIDOC ::: fast_cache.FastAPICache options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### Initialize In-Memory Cache Backend in FastAPI Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/in_memory.md Demonstrates how to import and initialize `FastAPICache` with `InMemoryBackend` in a FastAPI application. The `namespace` parameter is optional and provides a prefix for all cache keys. ```python from fast_cache import FastAPICache, InMemoryBackend cache = FastAPICache() backend = InMemoryBackend(namespace="myapp-cache") cache.init_app(app, backend) ``` -------------------------------- ### MongoDBBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Provides API documentation for the MongoDB cache backend, utilizing a MongoDB database for persistent cache storage. ```APIDOC ::: fast_cache.MongoDBBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### FirestoreBackend API Reference Source: https://github.com/devbijay/fast-cache/blob/main/docs/api.md Documents the Firestore cache backend, integrating with Google Cloud Firestore for scalable and flexible caching. ```APIDOC ::: fast_cache.FirestoreBackend options: show_source: true show_signature: true show_root_heading: true ``` -------------------------------- ### Access Cache Backend via Dependency Injection in FastAPI Source: https://github.com/devbijay/fast-cache/blob/main/README.md Illustrates how to inject the `CacheBackend` instance into a FastAPI endpoint using `Depends(cache.get_cache)`. This allows for manual control over caching logic, including retrieving, storing with expiration, and generating new data if not cached. ```python from fastapi import Depends from fast_cache import cache, CacheBackend from typing import Annotated @app.get("/api/data") async def get_data(cache_backend: Annotated[CacheBackend, Depends(cache.get_cache)]): # Try to get from cache cached_data = await cache_backend.aget("api:data") if cached_data: return cached_data # Generate new data data = await fetch_expensive_api_data() # Store in cache for 1 hour await cache_backend.aset("api:data", data, expire=3600) return data ``` -------------------------------- ### Inject DynamoDB Cache Backend into FastAPI Endpoints Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Illustrates how to use FastAPI's dependency injection system to provide the `DynamoDBBackend` instance directly to endpoint functions. This approach offers full control and improves testability by making the cache backend an explicit dependency. ```python from fastapi import Depends from typing import Annotated @app.get("/di/set") async def set_cache( cache_backend: Annotated[DynamoDBBackend, Depends(cache.get_cache)], key: str, value: str, ): await cache_backend.aset(key, value, expire=60) return {"set": True} @app.get("/di/get") async def get_cache( cache_backend: Annotated[DynamoDBBackend, Depends(cache.get_cache)], key: str, ): value = await cache_backend.aget(key) return {"value": value} ``` -------------------------------- ### Access Cache Backend via Dependency Injection in FastAPI Source: https://github.com/devbijay/fast-cache/blob/main/docs/index.md Illustrates how to inject the cache backend directly into a FastAPI endpoint using `Depends(cache.get_cache)`. This approach provides full control over caching logic, allowing for manual cache key generation, checking for cached values, and setting new values with a custom expiration after an expensive operation. ```python from fastapi import Depends from typing import Annotated @app.get("/expensive-direct") async def expensive_operation_direct( x: int, cache_backend: Annotated[InMemoryBackend, Depends(cache.get_cache)], ): cache_key = f"expensive:{x}" # Try to get from cache cached = await cache_backend.aget(cache_key) if cached is not None: return {"result": cached, "cached": True} # Simulate expensive work result = x * 2 await cache_backend.aset(cache_key, result, expire=60) return {"result": result, "cached": False} ``` -------------------------------- ### Bypass Cache for a Function Call Source: https://github.com/devbijay/fast-cache/blob/main/README.md Demonstrates how to explicitly bypass the cache when calling a function that is configured to use fast-cache, by passing the `skip_cache=True` argument to the function. ```python weather = await get_weather("New York", skip_cache=True) # Bypasses cache ``` -------------------------------- ### Cache FastAPI Endpoint with PostgresBackend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/postgres.md Illustrates how to apply caching to a FastAPI endpoint using the @cache.cached decorator, storing the results in the configured PostgresBackend for a specified duration. ```Python @app.get("/expensive") @cache.cached(expire=120) async def expensive_operation(x: int): # This result will be cached in Postgres for 2 minutes return {"result": x * 2} ``` -------------------------------- ### Cache Synchronous FastAPI Endpoint with @cache.cached Decorator Source: https://github.com/devbijay/fast-cache/blob/main/docs/index.md Shows how to apply the `@cache.cached` decorator to a synchronous FastAPI endpoint. This demonstrates that FastAPI Cachekit seamlessly supports caching for both asynchronous and synchronous functions with a simple decorator and a specified expiration time. ```python @app.get("/expensive-sync") @cache.cached(expire=60) def expensive_operation_sync(x: int): # Simulate expensive work return {"result": x * 3} ``` -------------------------------- ### Cache FastAPI Endpoint with @cache.cached Decorator Source: https://github.com/devbijay/fast-cache/blob/main/docs/index.md Demonstrates how to automatically cache the result of an asynchronous FastAPI endpoint using the `@cache.cached` decorator. It initializes an `InMemoryBackend` and applies the decorator with an expiration time of 60 seconds, simulating an expensive operation. ```python from fast_cache import cache, InMemoryBackend backend = InMemoryBackend() cache.init_app(app, backend) @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): # Simulate expensive work return {"result": x * 2} ``` -------------------------------- ### Cache FastAPI Endpoint with Custom Key and Namespace Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/dynamodb.md Demonstrates advanced usage of the `@cache.cached` decorator, allowing for custom cache key generation using a `key_builder` lambda function and specifying a unique `namespace` to prevent key collisions. ```python @app.get("/custom") @cache.cached( expire=120, key_builder=lambda x: f"custom:{x}", namespace="special" ) async def custom_cache(x: int): return {"value": x} ``` -------------------------------- ### Cache FastAPI Endpoint with MongoDB Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/mongodb.md Illustrates how to apply caching to a FastAPI endpoint using the `@cache.cached` decorator. The result of the `expensive_operation` will be stored in the configured MongoDB cache for 120 seconds, demonstrating automatic caching of API responses with a defined expiration. ```python @app.get("/expensive") @cache.cached(expire=120) async def expensive_operation(x: int): # This result will be cached in Postgres for 2 minutes return {"result": x * 2} ``` -------------------------------- ### Cache FastAPI Endpoint with Memcached Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/memcached.md Illustrates how to use the @cache.cached decorator to cache the result of a FastAPI endpoint in Memcached for a specified duration. ```python @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): # This result will be cached in Memcached for 60 seconds return {"result": x * 2} ``` -------------------------------- ### Cache FastAPI Endpoint with In-Memory Backend Source: https://github.com/devbijay/fast-cache/blob/main/docs/backends/in_memory.md Shows how to use the `@cache.cached` decorator on a FastAPI endpoint to cache its response in memory for a specified duration (e.g., 60 seconds). The result of the decorated function will be stored and retrieved from the cache. ```python @app.get("/expensive") @cache.cached(expire=60) async def expensive_operation(x: int): # This result will be cached in memory for 60 seconds return {"result": x * 2} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.