Fubuki's Built-in Caching Feature

Fubuki's Built-in Caching Feature

⚠️
The caching feature in Fubuki is currently under development. As such, it may not function as expected and could contain bugs or incomplete features. Use it with caution in production environments and report any issues you encounter to help improve the implementation.

Overview

Fubuki provides a built-in caching mechanism to help improve the performance of your applications by reducing redundant data processing and network requests. This guide will walk you through the steps to set up and use the caching feature effectively.

Setting Up the Cache Handler

First, we need to set up a CacheHandler that manages the storage and retrieval of cached data. Below is an example of how to initialize a cache handler using Redis:

from fubuki.ext.cache.handler import RedisCacheHandler

cache_handler = RedisCacheHandler(redis_url="redis://localhost:6379")

Applying the Cache Decorator

Once the cache handler is set up, you can use the @cache decorator to enable caching for specific endpoints or functions. Here’s an example:

from fubuki.ext.cache.deco import cache

@cache(cache_handler, expire=60)  # Cache expiration time set to 60 seconds
async def get_data(request):
    # Your data processing logic here
    return JSONResponse({"data": "This is cached data"})

In this example, the get_data function is decorated with @cache, which means its response will be cached for 60 seconds. The caching key is generated based on the request method, path, headers, query parameters, and body content.

Customizing Cache Keys

You can customize how cache keys are generated by modifying the cache_key_parts in the decorator. This allows you to fine-tune which parts of the request should contribute to the cache key.

@cache(cache_handler, expire=120)
async def get_custom_data(request):
    # Custom cache key logic can be added here if needed
    return JSONResponse({"data": "This is custom cached data"})