### FastAPI Cache Quick Start Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Demonstrates a basic setup for fastapi-cache with a Redis backend, including initialization and applying the @cache decorator to an endpoint. ```python from collections.abc import AsyncIterator from contextlib import asynccontextmanager 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 @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: redis = aioredis.from_url("redis://localhost") FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache") yield app = FastAPI(lifespan=lifespan) @cache() async def get_cache(): return 1 @app.get("/") @cache(expire=60) async def index(): return dict(hello="world") ``` -------------------------------- ### Install fastapi-cache Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Installs the fastapi-cache library using pip. Supports optional backends for redis, memcache, and dynamodb. ```shell pip install fastapi-cache2 ``` ```shell pip install "fastapi-cache2[redis]" ``` ```shell pip install "fastapi-cache2[memcache]" ``` ```shell pip install "fastapi-cache2[dynamodb]" ``` -------------------------------- ### Get fastapi-cache Project Version Source: https://github.com/long2ice/fastapi-cache/blob/main/changelog.d/172.feature.md Demonstrates how to retrieve the project's version string using the `importlib.metadata` module. This is a standard Python practice for accessing package metadata. ```python import importlib.metadata __version__ = importlib.metadata.version("fastapi_cache") print(f"fastapi-cache version: {__version__}") ``` -------------------------------- ### Custom ORJsonCoder for FastAPI Cache Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Demonstrates how to create a custom coder by inheriting from `fastapi_cache.coder.Coder`. This example uses `orjson` for efficient JSON encoding and decoding, suitable for caching complex data structures. It includes the `encode` and `decode` methods, and shows its usage with the `@cache` decorator. ```python from typing import Any import orjson from fastapi.encoders import jsonable_encoder from fastapi_cache import Coder class ORJsonCoder(Coder): @classmethod def encode(cls, value: Any) -> bytes: return orjson.dumps( value, default=jsonable_encoder, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY, ) @classmethod def decode(cls, value: bytes) -> Any: return orjson.loads(value) @app.get("/") @cache(expire=60, coder=ORJsonCoder) async def index(): return dict(hello="world") ``` -------------------------------- ### Running Pytest with Coverage Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Provides shell commands to run tests using `pytest` and generate an HTML coverage report. This is useful for assessing the test coverage of the project. The commands execute the tests, generate the report, and open it in the default web browser. ```shell coverage run -m pytest coverage html xdg-open htmlcov/index.html ``` -------------------------------- ### FastAPI Cache Decorator Parameters Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Details the parameters available for the @cache decorator, including expiration time, namespace, coder, key builder, and header configuration. ```APIDOC Parameter | type | default | description ------------ | ----| --------- | -------- `expire` | `int` | | sets the caching time in seconds `namespace` | `str` | `""` | namespace to use to store certain cache items `coder` | `Coder` | `JsonCoder` | which coder to use, e.g. `JsonCoder` `key_builder` | `KeyBuilder` callable | `default_key_builder` | which key builder to use `injected_dependency_namespace` | `str` | `__fastapi_cache` | prefix for injected dependency keywords. `cache_status_header` | `str` | `X-FastAPI-Cache` | Name for the header on the response indicating if the request was served from cache; either `HIT` or `MISS`. ``` -------------------------------- ### Caching Pydantic Models with fastapi-cache Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Illustrates how to cache Pydantic models by ensuring correct return type annotations on the decorated endpoint function. ```python from .models import SomeModel, create_some_model @app.get("/foo") @cache(expire=60) async def foo() -> SomeModel: return create_some_model() ``` -------------------------------- ### Custom Request Key Builder for FastAPI Cache Source: https://github.com/long2ice/fastapi-cache/blob/main/README.md Illustrates creating a custom key builder function for `fastapi-cache`. This function generates a cache key based on the request method, URL, and query parameters, providing a more granular caching strategy. It demonstrates how to pass this custom builder to the `@cache` decorator. ```python from typing import Any from fastapi import Request, Response def request_key_builder( func, namespace: str = "", *, request: Request = None, response: Response = None, *args, **kwargs, ): return ":".join([ namespace, request.method.lower(), request.url.path, repr(sorted(request.query_params.items())) ]) @app.get("/") @cache(expire=60, key_builder=request_key_builder) async def index(): return dict(hello="world") ``` -------------------------------- ### Cache HTML Response Source: https://github.com/long2ice/fastapi-cache/blob/main/examples/redis/index.html This snippet demonstrates how to cache an HTML response in a FastAPI application using the fastapi-cache library. It shows a basic endpoint that returns cached HTML. ```python from fastapi import FastAPI from fastapi_cache import FastAPICache from fastapi_cache.backends.inmemory import InMemoryBackend app = FastAPI() @app.on_event("startup") async def startup(): FastAPICache.init(InMemoryBackend(), prefix="fastapi-cache") @app.get("/") async def read_root(): # In a real application, this would fetch or generate HTML return {"message": "

Hello, World!

"} # Example of how to use the cache decorator (assuming it's configured) # from fastapi_cache.decorator import cache # # @app.get("/cached-html") # @cache(expire=60) # Cache for 60 seconds # async def get_cached_html(): # # Fetch or generate HTML content here # return {"html": "Cached Content"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.