apifrom.performance.cache_optimizerο
Cache optimization utilities for APIFromAnything.
This module provides tools for optimizing cache performance in high-load scenarios, including cache strategy optimization, monitoring, and auto-tuning.
Overviewο
Classes
BaseMiddlewareOptimizedCacheMiddleware
Classesο
- BaseMiddleware(**options):bases: abc.ABC
Base middleware class for APIFromAnything.
Collects and analyzes cache performance metrics.
This class collects cache performance metrics such as hit rates, latency, and memory usage, and provides tools for analyzing and visualizing this data.
Initialize cache analytics.
- apifrom.performance.cache_optimizer.get_hot_keys(limit=10)ο
Get the most frequently accessed cache keys.
- param limit:
The maximum number of keys to return
- returns:
A list of (key, access_count) tuples
- apifrom.performance.cache_optimizer.get_large_keys(limit=10)ο
Get the largest cache keys by value size.
- param limit:
The maximum number of keys to return
- returns:
A list of (key, size) tuples
- apifrom.performance.cache_optimizer.print_summary()ο
Print a summary of the analytics data to the console.
- apifrom.performance.cache_optimizer.record_delete(key, value_size)ο
Record a cache delete operation.
- param key:
The cache key
- param value_size:
The size of the cached value in bytes
- apifrom.performance.cache_optimizer.record_error(key)ο
Record a cache error.
- param key:
The cache key
- apifrom.performance.cache_optimizer.record_hit(key, value_size, latency)ο
Record a cache hit.
- param key:
The cache key
- param value_size:
The size of the cached value in bytes
- param latency:
The cache lookup latency in seconds
- apifrom.performance.cache_optimizer.record_miss(key, latency)ο
Record a cache miss.
- param key:
The cache key
- param latency:
The cache lookup latency in seconds
- apifrom.performance.cache_optimizer.record_request()ο
Record a cache request.
- apifrom.performance.cache_optimizer.record_set(key, value_size, ttl)ο
Record a cache set operation.
- param key:
The cache key
- param value_size:
The size of the cached value in bytes
- param ttl:
The TTL in seconds
- apifrom.performance.cache_optimizer.reset()ο
Reset all analytics data.
- apifrom.performance.cache_optimizer.save(file_path)ο
Save the analytics data to a file.
- param file_path:
The path to save the data to
- apifrom.performance.cache_optimizer.to_dict()ο
Convert the analytics data to a dictionary.
- returns:
A dictionary representation of the analytics data
- apifrom.performance.cache_optimizer.to_json(pretty=True)ο
Convert the analytics data to a JSON string.
- param pretty:
Whether to format the JSON with indentation
- returns:
A JSON string representation of the analytics data
Base class for cache backends.
- class apifrom.performance.cache_optimizer.CacheOptimizer(cache_backend, strategy=None, analytics=None, auto_tune_interval=None, output_dir=None)[source]ο
- Parameters:
cache_backend (apifrom.middleware.cache_advanced.CacheBackend)
strategy (Optional[OptimizedCacheStrategy])
analytics (Optional[CacheAnalytics])
auto_tune_interval (Optional[int])
output_dir (Optional[str])
Optimizes caching for high-load scenarios.
This class provides tools for optimizing cache performance, including strategy optimization, monitoring, and auto-tuning.
Initialize a cache optimizer.
- param cache_backend:
The cache backend to optimize
- param strategy:
The optimization strategy to use
- param analytics:
The cache analytics instance to use
- param auto_tune_interval:
The interval in seconds at which to auto-tune
- param output_dir:
The directory to save analytics data to
- apifrom.performance.cache_optimizer.auto_tune()ο
Auto-tune caching parameters based on analytics.
- apifrom.performance.cache_optimizer.delete(key)ο
- :async:
Delete a value from the cache.
- param key:
The cache key
- returns:
True if the value was deleted, False otherwise
- apifrom.performance.cache_optimizer.get(key)ο
- :async:
Get a value from the cache with optimization.
- param key:
The cache key
- returns:
The cached value, or None if not found
- apifrom.performance.cache_optimizer.get_analytics()ο
Get the cache analytics.
- returns:
The cache analytics instance
- apifrom.performance.cache_optimizer.reset_analytics()ο
Reset the cache analytics.
- apifrom.performance.cache_optimizer.set(key, value, ttl=60)ο
- :async:
Set a value in the cache with optimization.
- param key:
The cache key
- param value:
The value to cache
- param ttl:
The TTL in seconds
- returns:
True if the value was cached, False otherwise
- OptimizedCacheMiddleware(cache_backend=None, ttl = 60, auto_tune = True, auto_tune_interval = 300, output_dir = None, compression = True, **options):bases: apifrom.middleware.base.BaseMiddleware
Middleware for adding optimized caching to an API.
This middleware adds optimized caching to an API, using the CacheOptimizer to optimize caching strategies based on request patterns.
Initialize the optimized cache middleware.
- param cache_backend:
The cache backend to use
- param ttl:
Default time-to-live in seconds
- param auto_tune:
Whether to auto-tune cache parameters
- param auto_tune_interval:
The interval to auto-tune cache parameters in seconds
- param output_dir:
The directory to save analytics to
- param compression:
Whether to compress cached responses
- param **options:
Additional options
- apifrom.performance.cache_optimizer._auto_tune()ο
- :async:
Auto-tune cache parameters based on analytics.
- apifrom.performance.cache_optimizer._cache_response(cache_key, response)ο
- :async:
Cache a response.
- param cache_key:
The cache key
- param response:
The response to cache
- apifrom.performance.cache_optimizer._generate_cache_key(request)ο
Generate a cache key for a request.
- param request:
The request to generate a key for
- returns:
The cache key
- apifrom.performance.cache_optimizer._get_from_cache(cache_key)ο
- :async:
Get a response from the cache.
- param cache_key:
The cache key
- returns:
The cached response, or None if not found
- apifrom.performance.cache_optimizer._is_cacheable(request, response)ο
Check if a response is cacheable.
- param request:
The request
- param response:
The response
- returns:
True if the response is cacheable, False otherwise
- apifrom.performance.cache_optimizer.clear_cache()ο
Clear the cache.
- apifrom.performance.cache_optimizer.dispatch(request, call_next)ο
- :async:
Process a request through the middleware.
- param request:
The request to process
- param call_next:
The next middleware in the chain
- returns:
The response from the next middleware
- apifrom.performance.cache_optimizer.get_analytics()ο
Get cache analytics.
- returns:
The cache analytics
- apifrom.performance.cache_optimizer.get_stats()ο
Get cache statistics.
- returns:
A dictionary of cache statistics
- apifrom.performance.cache_optimizer.process_request(request)ο
- :async:
Process a request (required by BaseMiddleware).
- param request:
The request to process
- returns:
The processed request
- apifrom.performance.cache_optimizer.process_response(response)ο
- :async:
Process a response (required by BaseMiddleware).
- param response:
The response to process
- returns:
The processed response
- apifrom.performance.cache_optimizer.save_analytics()ο
Save cache analytics to a file.
- returns:
The path to the saved file, or None if saving failed
- class apifrom.performance.cache_optimizer.OptimizedCacheStrategy(min_ttl=60, max_ttl=86400, hit_rate_threshold=0.8, compress_values=True, compress_keys=False, prefetch_keys=False, auto_tune=True)[source]ο
A cache strategy that optimizes caching based on runtime analytics.
This class provides cache optimization strategies such as TTL adjustment, key compression, and value compression, based on runtime analytics.
Initialize an optimized cache strategy.
- param min_ttl:
The minimum TTL in seconds
- param max_ttl:
The maximum TTL in seconds
- param hit_rate_threshold:
The hit rate threshold for TTL adjustment
- param compress_values:
Whether to compress cached values
- param compress_keys:
Whether to compress cache keys
- param prefetch_keys:
Whether to prefetch related keys
- param auto_tune:
Whether to auto-tune caching parameters
- apifrom.performance.cache_optimizer.get_optimized_ttl(key, default_ttl)ο
Get an optimized TTL for a key based on access patterns.
- param key:
The cache key
- param default_ttl:
The default TTL in seconds
- returns:
The optimized TTL in seconds
- apifrom.performance.cache_optimizer.optimize_key(key)ο
Optimize a cache key.
- param key:
The original cache key
- returns:
The optimized cache key
- apifrom.performance.cache_optimizer.optimize_value(value)ο
Optimize a cached value.
- param value:
The original value
- returns:
The optimized value
- apifrom.performance.cache_optimizer.record_hit(key)ο
Record a cache hit for a key.
- param key:
The cache key
- apifrom.performance.cache_optimizer.record_miss(key)ο
Record a cache miss for a key.
- param key:
The cache key
- apifrom.performance.cache_optimizer.record_set(key, ttl)ο
Record a cache set operation.
- param key:
The cache key
- param ttl:
The TTL in seconds
- class apifrom.performance.cache_optimizer.Request(request=None, path_params=None, method=None, path=None, query_params=None, headers=None, body=None, client_ip=None)[source]ο
Request class for APIFromAnything.
This class wraps a Starlette request and provides methods for accessing request data in a convenient way.
- apifrom.performance.cache_optimizer._requestο
The underlying Starlette request.
- apifrom.performance.cache_optimizer.path_paramsο
Path parameters extracted from the URL.
- apifrom.performance.cache_optimizer.query_paramsο
Query parameters extracted from the URL.
- apifrom.performance.cache_optimizer.headersο
HTTP headers.
- apifrom.performance.cache_optimizer.methodο
HTTP method.
- apifrom.performance.cache_optimizer.pathο
Request path.
- apifrom.performance.cache_optimizer._bodyο
Cached request body.
Initialize a new Request instance.
- param request:
The underlying Starlette request.
- param path_params:
Path parameters extracted from the URL.
- param method:
The HTTP method.
- param path:
The request path.
- param query_params:
Query parameters.
- param headers:
HTTP headers.
- param body:
Request body.
- param client_ip:
Client IP address.
- class apifrom.performance.cache_optimizer.Response(content=None, status_code=200, headers=None, content_type='application/json')[source]ο
Response class for APIFromAnything.
This class represents an HTTP response and provides methods for setting response data, status code, and headers.
- apifrom.performance.cache_optimizer.contentο
The response content.
- apifrom.performance.cache_optimizer.status_codeο
The HTTP status code.
- apifrom.performance.cache_optimizer.headersο
HTTP headers.
- apifrom.performance.cache_optimizer.content_typeο
The content type of the response.
Initialize a new Response instance.
- param content:
The response content.
- param status_code:
The HTTP status code.
- param headers:
HTTP headers.
- param content_type:
The content type of the response.