# FastAPI Session Cache

***

**1. Caching Session Data in a FastAPI Application with Memory Cache**

```python
from fastapi.security import HTTPBasicCredentials
from fastapi.security.http.basic import HTTPBasic
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from starlette.responses import JSONResponse

backend = MemoryBackend()
cache = FastAPICache(backend)

app = FastAPI()
security = HTTPBasic()

@app.get("/cached")
async def cached_route(credentials: HTTPBasicCredentials = security):
    username = credentials.username
    cached_data = await cache.get(username)
    if not cached_data:
        # Fetch data from database or external source
        data = ...
        await cache.set(username, data)
    return JSONResponse(content={"data": cached_data})
```

**2. Caching Session Data for Authenticated Users**

```python
from fastapi.security import OAuth2PasswordBearer
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from starlette.responses import JSONResponse

backend = MemoryBackend()
cache = FastAPICache(backend)

app = FastAPI()
security = OAuth2PasswordBearer(tokenUrl="/token")

@app.get("/cached")
async def cached_route(token: str = security):
    username = decode_jwt(token)
    cached_data = await cache.get(username)
    if not cached_data:
        # Fetch data from database or external source
        data = ...
        await cache.set(username, data)
    return JSONResponse(content={"data": cached_data})
```

**3. Using Cache Control Headers with FastAPI-Session-Cache**

```python
from fastapi.responses import Response
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

app = FastAPI()

@app.get("/cached")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    response = Response(content=data)
    await cache.set("my-data", response, expire=3600)
    return response
```

**4. Handling Cache Invalidation with FastAPI-Session-Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from starlette.requests import Request
from starlette.responses import JSONResponse

backend = MemoryBackend()
cache = FastAPICache(backend)

app = FastAPI()

@app.post("/invalidate")
async def invalidate_cache(request: Request):
    data = await request.json()
    key = data.get("key")
    await cache.delete(key)
    return JSONResponse(content={"success": True})
```

**5. Caching Session Data Per Route or Endpoint**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

app = FastAPI()

@app.get("/cached", tags=["cached-routes"])
@cache.cache(expire=3600)
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**6. Selective Caching of FastAPI Routes**

```python
from fastapi_cache import FastAPICache, config
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

config.cache_on=["/cached-route1", "/cached-route2"]

app = FastAPI()

@app.get("/cached-route1")
@cache.cache()
async def cached_route1():
    # Fetch data from database or external source
    data = ...
    return data
```

**7. Caching Data for a Specific Duration**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get(
    "/cached-with-duration",
    tags=["cached-routes"],
    responses={
        200: {"content": {"application/json": {"example": {"data": "cached data"}}}}
    },
)
@cache.cache(expire=3600)  # cache for 1 hour
async def cached_route_with_duration():
    # Fetch data from database or external source
    data = ...
    return data
```

**8. Using Cache-Control Header with FastAPI-Session-Cache**

```python
from fastapi.responses import Response
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(expire=3600, cache_control="max-age=3600")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**9. Caching Multiple Responses at Once**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached-multiple")
@cache.cache(expire=3600, multiple_keys=["key1", "key2", "key3"])
async def cached_route_multiple_keys():
    # Fetch data from database or external source
    data1 = ...
    data2 = ...
    data3 = ...
    return {"data1": data1, "data2": data2, "data3": data3}
```

**10. Excluding Certain Paths or Endpoints from Caching**

```python
from fastapi_cache import FastAPICache, config
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

config.cache_exclude=["/exclude-this-route"]

app = FastAPI()

@app.get("/cached")
@cache.cache()
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**11. Using the Custom Key Generator**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from typing import List

backend = MemoryBackend()
cache = FastAPICache(backend)

def custom_key_generator(request, *args, **kwargs):
    key = f"{request.method}:{request.path}"
    if args:
        key += f":{args[0]}"
    if kwargs:
        key += f":{kwargs['user_id']}"
    return key

app = FastAPI()

@app.get("/cached")
@cache.cache(key_generator=custom_key_generator)
async def cached_route(arg1: int, user_id: int):
    # Fetch data from database or external source
    data = ...
    return data
```

**12. Caching Session Data for Multiple Users**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
async def cached_route(user_id: int):
    cached_data = await cache.get(str(user_id))
    if not cached_data:
        # Fetch data from database or external source
        data = ...
        await cache.set(str(user_id), data)
    return data
```

**13. Fine-Grained Control over Cache Behavior**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from fastapi_cache.decorator import cache

backend = MemoryBackend()
cache = FastAPICache(backend)

# Cache the results for 3600 seconds
@cache.cache(expire=3600)
async def get_data():
    # Fetch data from database or external source
    data = ...
    return data
```

**14. Caching Data with Custom Metadata**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from typing import Dict

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(metadata={"user_id": 10, "role": "admin"})
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**15. Caching Data with a Different Cache Key**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(key="my-custom-key")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**16. Using the Cache Manager**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

# Cache the results for 3600 seconds
await cache.set("my-data", data, expire=3600)
cached_data = await cache.get("my-data")
```

**17. Caching a Single Request**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.single()
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**18. Caching a Request with a Custom Key**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.single(key="my-custom-key")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**19. Using the Cache Manager to Set Data**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

await cache.set("my-data", data)
```

**20. Using the Cache Manager to Delete Data**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

await cache.delete("my-data")
```

**21. Using the Cache Manager to Clear the Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

await cache.clear()
```

**22. Caching Data with a Custom Expiration Time**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(expire=3600)
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**23. Caching Data with a Custom Cache Key**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(key="my-custom-key")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**24. Caching Data with a Custom Cache Prefix**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(prefix="my-custom-prefix")
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**25. Caching Data with a Custom Cache Dependency**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(dependencies=[fastapi.Depends(my_custom_dependency)])
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**26. Caching Data with a Custom Cache Condition**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(condition=fastapi.Depends(my_custom_condition))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**27. Caching Data with a Custom Cache Expires**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(expires=fastapi.Depends(my_custom_expires))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**28. Caching Data with a Custom Cache Key Builder**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(key_builder=fastapi.Depends(my_custom_key_builder))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**29. Caching Data with a Custom Cache Serializer**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(serializer=fastapi.Depends(my_custom_serializer))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**30. Caching Data with a Custom Cache Deserializer**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(deserializer=fastapi.Depends(my_custom_deserializer))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**31. Caching Data with a Custom Cache Hasher**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(hasher=fastapi.Depends(my_custom_hasher))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**32. Caching Data with a Custom Cache Compressor**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(compressor=fastapi.Depends(my_custom_compressor))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**33. Caching Data with a Custom Cache Decompressor**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(decompressor=fastapi.Depends(my_custom_decompressor))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**34. Caching Data with a Custom Cache Encoder**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(encoder=fastapi.Depends(my_custom_encoder))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**35. Caching Data with a Custom Cache Decoder**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(decoder=fastapi.Depends(my_custom_decoder))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```

**36. Caching Data with a Custom Cache TTL**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend

backend = MemoryBackend()
cache = FastAPICache(backend)

@app.get("/cached")
@cache.cache(ttl=fastapi.Depends(my_custom_ttl))
async def cached_route():
    # Fetch data from database or external source
    data = ...
    return data
```
