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.

Overview

Classes

Functions

Classes

class apifrom.decorators.web_optimize.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)[source]
Parameters:

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.

apifrom.decorators.web_optimize.router

The router instance for managing routes.

Type:

Router

apifrom.decorators.web_optimize.middleware

List of middleware instances.

Type:

list

apifrom.decorators.web_optimize.debug

Whether to run in debug mode.

Type:

bool

apifrom.decorators.web_optimize.title

The title of the API.

Type:

str

apifrom.decorators.web_optimize.description

The description of the API.

Type:

str

apifrom.decorators.web_optimize.version

The version of the API.

Type:

str

apifrom.decorators.web_optimize.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.

class apifrom.decorators.web_optimize.APIProfiler(output_dir=None, enabled=True)[source]
Parameters:
  • output_dir (Optional[str])

  • enabled (bool)

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

class apifrom.decorators.web_optimize.CacheOptimizer(cache_backend, strategy=None, analytics=None, auto_tune_interval=None, output_dir=None)[source]
Parameters:

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

class apifrom.decorators.web_optimize.ConnectionPool(factory, settings=None, validate_func=None, close_func=None, metrics=None)[source]
Parameters:

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

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

class apifrom.decorators.web_optimize.PoolManager[source]

Manages multiple connection pools.

This class manages multiple connection pools for different resources, such as databases, APIs, or services.

Initialize a pool manager.

class apifrom.decorators.web_optimize.Web(title=None, description=None, theme='default', template=None)[source]
Parameters:
  • title (Optional[str])

  • description (Optional[str])

  • theme (str)

  • template (Optional[str])

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.

apifrom.decorators.web_optimize.title

The title to display in the HTML page

Type:

str

apifrom.decorators.web_optimize.description

A description of the endpoint to display in the HTML

Type:

str

apifrom.decorators.web_optimize.theme

The theme to use for styling (‘default’, ‘dark’, ‘light’)

Type:

str

apifrom.decorators.web_optimize.template

Optional path to a custom HTML template

Type:

str

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

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.

apifrom.decorators.web_optimize.title

The title to display in the HTML page

Type:

str

apifrom.decorators.web_optimize.description

A description of the endpoint to display in the HTML

Type:

str

apifrom.decorators.web_optimize.theme

The theme to use for styling (‘default’, ‘dark’, ‘light’)

Type:

str

apifrom.decorators.web_optimize.template

Optional path to a custom HTML template

Type:

str

apifrom.decorators.web_optimize.enable_profiling

Whether to enable profiling

Type:

bool

apifrom.decorators.web_optimize.enable_caching

Whether to enable caching

Type:

bool

apifrom.decorators.web_optimize.cache_ttl

Time-to-live for cached responses in seconds

Type:

int

apifrom.decorators.web_optimize.enable_connection_pooling

Whether to enable connection pooling

Type:

bool

apifrom.decorators.web_optimize.pool_name

Name of the connection pool to use

Type:

str

apifrom.decorators.web_optimize.enable_request_coalescing

Whether to enable request coalescing

Type:

bool

apifrom.decorators.web_optimize.coalesce_window_time

Time window for coalescing requests in seconds

Type:

float

apifrom.decorators.web_optimize.coalesce_max_requests

Maximum number of requests to coalesce

Type:

int

apifrom.decorators.web_optimize.enable_batch_processing

Whether to enable batch processing

Type:

bool

apifrom.decorators.web_optimize.batch_size

Maximum batch size for batch processing

Type:

int

apifrom.decorators.web_optimize.batch_wait_time

Maximum wait time for batch processing in seconds

Type:

float

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

apifrom.decorators.web_optimize.__call__(func)

Apply the WebOptimize decorator to a function.

param func:

The function to decorate

returns:

The decorated function

apifrom.decorators.web_optimize.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

apifrom.decorators.web_optimize.get_cache_optimizer()
:classmethod:

Get the class-level cache optimizer instance.

apifrom.decorators.web_optimize.get_performance_metrics()
:classmethod:

Get performance metrics from all optimization components.

returns:

A dictionary of performance metrics

apifrom.decorators.web_optimize.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

apifrom.decorators.web_optimize.get_pool_manager()
:classmethod:

Get the class-level pool manager instance.

apifrom.decorators.web_optimize.get_profiler()
:classmethod:

Get the class-level profiler instance.

apifrom.decorators.web_optimize.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

apifrom.decorators.web_optimize.batch_process(batch_size=100, max_wait_time=0.1, process_func=None, auto_process=True)[source]
Parameters:
  • batch_size (int)

  • max_wait_time (float)

  • process_func (Optional[BatchFunction])

  • auto_process (bool)

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

apifrom.decorators.web_optimize.coalesce_requests(window_time=0.1, max_requests=None)[source]
Parameters:
  • window_time (float)

  • max_requests (Optional[int])

Return type:

Callable[[Callable[Ellipsis, R]], Callable[Ellipsis, R]]

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