apifrom.decorators.web_optimize =============================== Web Optimization Decorator for the APIFromAnything library. This module provides the WebOptimize decorator, which combines the Web decorator with performance optimization features like profiling, caching, connection pooling, request coalescing, and batch processing. .. py:currentmodule:: apifrom.decorators.web_optimize Overview -------- **Classes** * :py:class:`API` * :py:class:`APIProfiler` * :py:class:`CacheOptimizer` * :py:class:`ConnectionPool` * :py:class:`MemoryCacheBackend` * :py:class:`PoolManager` * :py:class:`Web` * :py:class:`WebOptimize` **Functions** * :py:func:`batch_process` * :py:func:`coalesce_requests` Classes ------- .. py:class:: API(debug = False, title = 'APIFromAnything API', description = 'API created with APIFromAnything', version = '1.0.0', docs_url = '/docs', openapi_config = None, swagger_ui_config = None, enable_docs = True) Main application container for APIFromAnything. This class serves as the central registry for all API endpoints, middleware, and configuration. It provides methods for registering endpoints, middleware, and starting the server. .. attribute:: router The router instance for managing routes. :type: Router .. attribute:: middleware List of middleware instances. :type: list .. attribute:: debug Whether to run in debug mode. :type: bool .. attribute:: title The title of the API. :type: str .. attribute:: description The description of the API. :type: str .. attribute:: version The version of the API. :type: str .. attribute:: docs_url The URL for the API documentation. :type: str Initialize a new API instance. :param debug: Whether to run in debug mode. :param title: The title of the API. :param description: The description of the API. :param version: The version of the API. :param docs_url: The URL for the API documentation. :param openapi_config: Configuration for OpenAPI documentation. :param swagger_ui_config: Configuration for Swagger UI. :param enable_docs: Whether to enable API documentation. .. py:class:: APIProfiler(output_dir = None, enabled = True) Profiles API endpoints to measure performance and identify bottlenecks. This class provides tools for profiling API endpoints, measuring response times, memory usage, and CPU usage, and generating profile reports. Initialize an API profiler. :param output_dir: The directory to save profile reports to (defaults to current directory) :param enabled: Whether profiling is enabled .. py:class:: CacheOptimizer(cache_backend, strategy = None, analytics = None, auto_tune_interval = None, output_dir = None) 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 .. py:class:: ConnectionPool(factory, settings = None, validate_func = None, close_func = None, metrics = None) A generic connection pool for managing connections to external resources. This class provides a pool of connections to external resources, such as databases, APIs, or services, and manages their lifecycle. Initialize a connection pool. :param factory: A factory function that creates new connections :param settings: The connection pool settings :param validate_func: A function that validates connections :param close_func: A function that closes connections :param metrics: A metrics instance for collecting pool metrics .. py:class:: MemoryCacheBackend(max_items = 1000, max_size_bytes = 50 * 1024 * 1024, eviction_policy = None):bases: CacheBackend In-memory cache backend. Initialize the memory cache backend. :param max_items: Maximum number of items to store :param max_size_bytes: Maximum cache size in bytes :param eviction_policy: The eviction policy to use .. py:class:: PoolManager Manages multiple connection pools. This class manages multiple connection pools for different resources, such as databases, APIs, or services. Initialize a pool manager. .. py:class:: Web(title = None, description = None, theme = 'default', template = None) Decorator that enhances API endpoints with HTML rendering capabilities. When an endpoint decorated with @Web is accessed with an Accept header that includes 'text/html' (e.g., from a web browser), the response will be rendered as HTML. Otherwise, the response will be returned as JSON (the default API behavior). This makes API endpoints more user-friendly when accessed directly from a web browser, while maintaining their programmatic API functionality. .. attribute:: title The title to display in the HTML page :type: str .. attribute:: description A description of the endpoint to display in the HTML :type: str .. attribute:: theme The theme to use for styling ('default', 'dark', 'light') :type: str .. attribute:: template Optional path to a custom HTML template :type: str .. admonition:: Example ```python from apifrom.core.app import API from apifrom.decorators.web import Web app = API() @app.api('/users') @Web(title="Users API", description="Get a list of users") def get_users(request): return [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"} ] ``` Initialize the Web decorator. :param title: The title to display in the HTML page :param description: A description of the endpoint to display in the HTML :param theme: The theme to use for styling ('default', 'dark', 'light') :param template: Optional path to a custom HTML template .. py:class:: WebOptimize(title = None, description = None, theme = 'default', template = None, enable_profiling = False, enable_caching = False, cache_ttl = 60, enable_connection_pooling = False, pool_name = None, enable_request_coalescing = False, coalesce_window_time = 0.5, coalesce_max_requests = 10, enable_batch_processing = False, batch_size = 10, batch_wait_time = 0.5):bases: apifrom.decorators.web.Web Decorator that combines the Web decorator with performance optimization features. This decorator enhances API endpoints with HTML rendering capabilities and performance optimization features like profiling, caching, connection pooling, request coalescing, and batch processing. .. attribute:: title The title to display in the HTML page :type: str .. attribute:: description A description of the endpoint to display in the HTML :type: str .. attribute:: theme The theme to use for styling ('default', 'dark', 'light') :type: str .. attribute:: template Optional path to a custom HTML template :type: str .. attribute:: enable_profiling Whether to enable profiling :type: bool .. attribute:: enable_caching Whether to enable caching :type: bool .. attribute:: cache_ttl Time-to-live for cached responses in seconds :type: int .. attribute:: enable_connection_pooling Whether to enable connection pooling :type: bool .. attribute:: pool_name Name of the connection pool to use :type: str .. attribute:: enable_request_coalescing Whether to enable request coalescing :type: bool .. attribute:: coalesce_window_time Time window for coalescing requests in seconds :type: float .. attribute:: coalesce_max_requests Maximum number of requests to coalesce :type: int .. attribute:: enable_batch_processing Whether to enable batch processing :type: bool .. attribute:: batch_size Maximum batch size for batch processing :type: int .. attribute:: batch_wait_time Maximum wait time for batch processing in seconds :type: float .. admonition:: Example ```python from apifrom.core.app import API from apifrom.decorators.web_optimize import WebOptimize app = API() @app.api('/users') @WebOptimize( title="Users API", description="Get a list of users", enable_caching=True, cache_ttl=60, enable_profiling=True ) def get_users(request): return [ {"id": 1, "name": "Alice", "email": "alice@example.com"}, {"id": 2, "name": "Bob", "email": "bob@example.com"}, {"id": 3, "name": "Charlie", "email": "charlie@example.com"} ] ``` Initialize the WebOptimize decorator. :param title: The title to display in the HTML page :param description: A description of the endpoint to display in the HTML :param theme: The theme to use for styling ('default', 'dark', 'light') :param template: Optional path to a custom HTML template :param enable_profiling: Whether to enable profiling :param enable_caching: Whether to enable caching :param cache_ttl: Time-to-live for cached responses in seconds :param enable_connection_pooling: Whether to enable connection pooling :param pool_name: Name of the connection pool to use :param enable_request_coalescing: Whether to enable request coalescing :param coalesce_window_time: Time window for coalescing requests in seconds :param coalesce_max_requests: Maximum number of requests to coalesce :param enable_batch_processing: Whether to enable batch processing :param batch_size: Maximum batch size for batch processing :param batch_wait_time: Maximum wait time for batch processing in seconds .. :: _cache_optimizer .. :: _pool_manager .. :: _profiler .. :: batch_size .. :: batch_wait_time .. :: cache_ttl .. :: coalesce_max_requests .. :: coalesce_window_time .. :: enable_batch_processing .. :: enable_caching .. :: enable_connection_pooling .. :: enable_profiling .. :: enable_request_coalescing .. :: pool_name .. method:: __call__(func) Apply the WebOptimize decorator to a function. :param func: The function to decorate :returns: The decorated function .. method:: create_pool(name, min_size = 5, max_size = 20, validate_func = None) :classmethod: Create a connection pool with the specified settings. :param name: Name of the connection pool :param min_size: Minimum number of connections in the pool :param max_size: Maximum number of connections in the pool :param validate_func: Function to validate connections :returns: A ConnectionPool instance .. method:: get_cache_optimizer() :classmethod: Get the class-level cache optimizer instance. .. method:: get_performance_metrics() :classmethod: Get performance metrics from all optimization components. :returns: A dictionary of performance metrics .. method:: get_pool(name) :classmethod: Get a connection pool by name. :param name: Name of the connection pool :returns: A ConnectionPool instance, or None if not found .. method:: get_pool_manager() :classmethod: Get the class-level pool manager instance. .. method:: get_profiler() :classmethod: Get the class-level profiler instance. .. method:: optimize(title = None, description = None, theme = 'default', template = None, enable_profiling = True, enable_caching = True, cache_ttl = 60, enable_connection_pooling = True, pool_name = None, enable_request_coalescing = True, coalesce_window_time = 0.5, coalesce_max_requests = 10, enable_batch_processing = False, batch_size = 10, batch_wait_time = 0.5) :classmethod: Class method to create a WebOptimize decorator with the specified settings. This is a convenience method for creating a WebOptimize decorator with common optimization settings. :param title: The title to display in the HTML page :param description: A description of the endpoint to display in the HTML :param theme: The theme to use for styling ('default', 'dark', 'light') :param template: Optional path to a custom HTML template :param enable_profiling: Whether to enable profiling :param enable_caching: Whether to enable caching :param cache_ttl: Time-to-live for cached responses in seconds :param enable_connection_pooling: Whether to enable connection pooling :param pool_name: Name of the connection pool to use :param enable_request_coalescing: Whether to enable request coalescing :param coalesce_window_time: Time window for coalescing requests in seconds :param coalesce_max_requests: Maximum number of requests to coalesce :param enable_batch_processing: Whether to enable batch processing :param batch_size: Maximum batch size for batch processing :param batch_wait_time: Maximum wait time for batch processing in seconds :returns: A WebOptimize decorator with the specified settings Functions --------- .. py:function:: batch_process(batch_size = 100, max_wait_time = 0.1, process_func = None, auto_process = True) Decorator for batch processing. This decorator groups calls to a function into batches and processes them together. :param batch_size: The maximum number of items in a batch :param max_wait_time: The maximum time to wait for a batch to fill in seconds :param process_func: A function to process batches :param auto_process: Whether to automatically process batches when filled :returns: A decorator function .. py:function:: coalesce_requests(window_time = 0.1, max_requests = None) Decorator for coalescing multiple identical requests into a single request. :param window_time: Time window in seconds to coalesce requests. :type window_time: float :param max_requests: Maximum number of requests to coalesce. :type max_requests: int, optional :returns: Decorated function that coalesces requests. :rtype: Callable