# FastAPI Cache

***

**1. Simple In-Memory Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend

cache = FastAPICache(
    backend=InMemoryBackend()
)
```

**2. Redis Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend

cache = FastAPICache(
    backend=RedisBackend(host="localhost", port=6379)
)
```

**3. Memcached Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memcached import MemcachedBackend

cache = FastAPICache(
    backend=MemcachedBackend(host="localhost", port=11211)
)
```

**4. MongoDB Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.mongodb import MongoDBBackend

cache = FastAPICache(
    backend=MongoDBBackend(host="localhost", port=27017, database="cache")
)
```

**5. PostgreSQL Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.sqlalchemy import SQLAlchemyBackend

engine = create_engine("postgresql://user:password@host:port/database")
cache = FastAPICache(
    backend=SQLAlchemyBackend(engine, table_name="cache")
)
```

**6. SQLite Cache**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.sqlalchemy import SQLAlchemyBackend

engine = create_engine("sqlite:///cache.db")
cache = FastAPICache(
    backend=SQLAlchemyBackend(engine, table_name="cache")
)
```

**7. Caching a Function Output**

```python
@app.get("/")
async def example(cache: FastAPICache = Depends()):
    result = await cache.get_or_set("my-key", some_expensive_function)
    return result
```

**8. Caching with Expiry Time**

```python
@app.get("/")
async def example(cache: FastAPICache = Depends()):
    result = await cache.get_or_set("my-key", some_expensive_function, expire=300)
    return result
```

**9. Caching with Key Prefix**

```python
cache = FastAPICache(key_prefix="my-prefix")

@app.get("/")
async def example(cache: FastAPICache = Depends()):
    result = await cache.get_or_set("my-key", some_expensive_function)
    return result
```

**10. Caching Response Data**

```python
@app.get("/")
async def example(cache: FastAPICache = Depends()):
    response = Response("Hello, world!")
    response = await cache.cache_response(response, "my-key")
    return response
```

**11. Invalidate Cache Items**

```python
cache.invalidate("my-key")
```

**12. Invalidate Cache Items with Prefix**

```python
cache.invalidate_prefix("my-prefix")
```

**13. Clear Cache**

```python
cache.clear()
```

**14. Cache Object with Overwrite Policy**

```python
result = await cache.get_or_set(
    "my-key", 
    some_expensive_function, 
    overwrite=False
)
```

**15. Configure Default Cache Duration**

```python
cache = FastAPICache(default_expire=300)
```

**16. Use a Cache Middleware**

```python
app.add_middleware(
    FastAPICacheMiddleware, 
    cache=cache
)
```

**17. Inject Cache into Dependency Injection**

```python
@app.get("/")
async def example(cache: FastAPICache = Depends()):
    ...
```

**18. Accessing Cache Stats (backend-dependent)**

```python
stats = cache.stats()
```

**19. Caching with a Key-Value Pair**

```python
await cache.set("my-key", "my-value")
value = await cache.get("my-key")
```

**20. Caching with a Dictionary**

```python
await cache.set_dict("my-dict", {"key1": "value1", "key2": "value2"})
value = await cache.get_dict("my-dict")
```

**21. Caching with a List**

```python
await cache.set_list("my-list", ["value1", "value2", "value3"])
value = await cache.get_list("my-list")
```

**22. Caching with a Set**

```python
await cache.set_set("my-set", {"value1", "value2", "value3"})
value = await cache.get_set("my-set")
```

**23. Caching with a ZSet**

```python
await cache.set_zset("my-zset", [("value1", 1), ("value2", 2), ("value3", 3)])
value = await cache.get_zset("my-zset")
```

**24. Caching with a Bitmap**

```python
await cache.set_bitmap("my-bitmap", [True, False, True])
value = await cache.get_bitmap("my-bitmap")
```

**25. Caching with a HyperLogLog**

```python
await cache.set_hyperloglog("my-hyperloglog")
value = await cache.get_hyperloglog("my-hyperloglog")
```

**26. Caching with a GeoSet**

```python
await cache.set_geoset("my-geoset", [("value1", 10.0, 20.0), ("value2", 30.0, 40.0)])
value = await cache.get_geoset("my-geoset")
```

**27. Caching with a Stream**

```python
await cache.set_stream("my-stream", ["value1", "value2", "value3"])
value = await cache.get_stream("my-stream")
```

**28. Caching with a TimeSeries**

```python
await cache.set_timeseries("my-timeseries", {"value1": 10, "value2": 20})
value = await cache.get_timeseries("my-timeseries")
```

**29. Caching with a WebSocket Channel**

```python
await cache.set_websocket_channel("my-channel", "my-value")
value = await cache.get_websocket_channel("my-channel")
```

**30. Caching with a Crontab Schedule**

```python
from fastapi_cache import schedulers

scheduler = schedulers.CrontabScheduler(cache)
scheduler.add_job(update_cache, "0 0 * * *")  # Run daily at midnight
```

**31. Caching with a Time of Day Schedule**

```python
from fastapi_cache import schedulers

scheduler = schedulers.TimeOfDayScheduler(cache)
scheduler.add_job(update_cache, "00:00:00")  # Run daily at midnight
```

**32. Caching with a Rate Limiter**

```python
from fastapi_cache import rate_limiters

rate_limiter = rate_limiters.FixedWindowRateLimiter(cache, limit=100, period=60)
```

**33. Caching with a Sliding Window Rate Limiter**

```python
from fastapi_cache import rate_limiters

rate_limiter = rate_limiters.SlidingWindowRateLimiter(cache, limit=100, period=60, window=10)
```

**34. Caching with a Leaky Bucket Rate Limiter**

```python
from fastapi_cache import rate_limiters

rate_limiter = rate_limiters.LeakyBucketRateLimiter(cache, rate=100, capacity=1000)
```

**35. Caching with a Token Bucket Rate Limiter**

```python
from fastapi_cache import rate_limiters

rate_limiter = rate_limiters.TokenBucketRateLimiter(cache, rate=100, capacity=1000)
```

**36. Caching with a RedisPubSub Backend**

```python
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redispubsub import RedisPubSubBackend

cache = FastAPICache(
    backend=RedisPubSubBackend(host="localhost", port=6379, channel="my-channel")
)
```
