apifrom.performance.optimization

Optimization utilities for APIFromAnything.

This module provides tools for analyzing and optimizing API performance, including optimization configuration, recommendation generation, and auto-tuning.

Overview

Classes

Classes

class apifrom.performance.optimization.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

BaseMiddleware(**options):bases: abc.ABC

Base middleware class for APIFromAnything.

This abstract class defines the interface for middleware components. Middleware components can process requests and responses.

apifrom.performance.optimization.options

Options for the middleware.

Type:

dict

Initialize a new BaseMiddleware instance.

param **options:

Options for the middleware.

class apifrom.performance.optimization.OptimizationAnalyzer(config=None, profiler=None, output_dir=None)[source]
Parameters:

Analyzes API performance and generates optimization recommendations.

This class provides tools for analyzing API performance, generating optimization recommendations, and applying optimizations.

Initialize an optimization analyzer.

param config:

The optimization configuration

param profiler:

An existing APIProfiler instance

param output_dir:

The directory to save optimization data to

apifrom.performance.optimization._analyze_profile_reports(reports)

Analyze profile reports and generate optimization recommendations.

param reports:

The profile reports to analyze

returns:

A list of optimization recommendations

apifrom.performance.optimization._analyze_system_stats()

Analyze system statistics and generate optimization recommendations.

returns:

A list of optimization recommendations

apifrom.performance.optimization._generate_code_specific_recommendations()

Generate code-specific optimization recommendations.

This method analyzes the codebase to find potential performance issues.

returns:

A list of optimization recommendations

apifrom.performance.optimization._generate_general_recommendations()

Generate general optimization recommendations.

returns:

A list of optimization recommendations

apifrom.performance.optimization._get_system_stats()

Get system statistics.

returns:

A dictionary of system statistics

apifrom.performance.optimization._save_recommendations()

Save optimization recommendations to files.

apifrom.performance.optimization.analyze()

Analyze API performance and generate optimization recommendations.

returns:

A list of optimization recommendations

apifrom.performance.optimization.get_optimization_config()

Get the optimization configuration.

returns:

The optimization configuration

apifrom.performance.optimization.get_recommendations()

Get optimization recommendations.

returns:

A list of optimization recommendations

apifrom.performance.optimization.print_summary()

Print a summary of the optimization analysis to the console.

apifrom.performance.optimization.set_optimization_config(config)

Set the optimization configuration.

param config:

The optimization configuration

class apifrom.performance.optimization.OptimizationConfig(level=OptimizationLevel.BALANCED, enable_caching=True, enable_connection_pooling=True, enable_profiling=True, enable_request_coalescing=False, enable_request_throttling=False, enable_auto_tuning=True, enable_eager_loading=False, enable_circuit_breaker=False, slow_response_threshold_ms=500, high_memory_threshold_mb=500, high_cpu_threshold_percent=80, high_error_rate_threshold=0.05, optimization_interval=3600)[source]
Parameters:
  • level (OptimizationLevel)

  • enable_caching (bool)

  • enable_connection_pooling (bool)

  • enable_profiling (bool)

  • enable_request_coalescing (bool)

  • enable_request_throttling (bool)

  • enable_auto_tuning (bool)

  • enable_eager_loading (bool)

  • enable_circuit_breaker (bool)

  • slow_response_threshold_ms (int)

  • high_memory_threshold_mb (int)

  • high_cpu_threshold_percent (int)

  • high_error_rate_threshold (float)

  • optimization_interval (int)

Configuration for optimizing APIFromAnything.

This class defines the configuration for optimizing the APIFromAnything application for high-load scenarios.

Initialize optimization configuration.

param level:

The optimization level

param enable_caching:

Whether to enable caching

param enable_connection_pooling:

Whether to enable connection pooling

param enable_profiling:

Whether to enable profiling

param enable_request_coalescing:

Whether to enable request coalescing

param enable_request_throttling:

Whether to enable request throttling

param enable_auto_tuning:

Whether to enable auto-tuning

param enable_eager_loading:

Whether to enable eager loading

param enable_circuit_breaker:

Whether to enable circuit breaker

param slow_response_threshold_ms:

The slow response threshold in milliseconds

param high_memory_threshold_mb:

The high memory threshold in megabytes

param high_cpu_threshold_percent:

The high CPU threshold in percent

param high_error_rate_threshold:

The high error rate threshold (0.0 to 1.0)

param optimization_interval:

The interval between optimizations in seconds

apifrom.performance.optimization.create_aggressive()
:classmethod:

Create an aggressive optimization configuration.

These settings are optimized for maximum performance.

returns:

OptimizationConfig instance

apifrom.performance.optimization.create_balanced()
:classmethod:

Create a balanced optimization configuration.

These settings provide a balance between performance and overhead.

returns:

OptimizationConfig instance

apifrom.performance.optimization.create_minimal()
:classmethod:

Create a minimal optimization configuration.

These settings are optimized for minimal overhead.

returns:

OptimizationConfig instance

apifrom.performance.optimization.load(file_path)
:classmethod:

Load configuration from a file.

param file_path:

The path to load the configuration from

returns:

OptimizationConfig instance

apifrom.performance.optimization.save(file_path)

Save the configuration to a file.

param file_path:

The path to save the configuration to

apifrom.performance.optimization.to_dict()

Convert the configuration to a dictionary.

returns:

A dictionary representation of the configuration

apifrom.performance.optimization.to_json(pretty=True)

Convert the configuration to a JSON string.

param pretty:

Whether to format the JSON with indentation

returns:

A JSON string representation of the configuration

OptimizationLevel:bases: enum.Enum

Optimization level for the APIFromAnything application.

This enum defines the level of optimization to apply to the APIFromAnything application.

class apifrom.performance.optimization.OptimizationRecommendation(title, description, action, priority=3, affected_endpoints=None, affected_components=None, estimated_impact=None, code_examples=None)[source]
Parameters:
  • title (str)

  • description (str)

  • action (str)

  • priority (int)

  • affected_endpoints (Optional[List[str]])

  • affected_components (Optional[List[str]])

  • estimated_impact (Optional[str])

  • code_examples (Optional[List[str]])

Represents a performance optimization recommendation.

This class provides methods for generating and applying optimization recommendations based on performance data.

Initialize an optimization recommendation.

param title:

The recommendation title

param description:

The recommendation description

param action:

The recommended action

param priority:

The recommendation priority (1-5, 1 is highest)

param affected_endpoints:

The affected API endpoints

param affected_components:

The affected components

param estimated_impact:

The estimated impact of the recommendation

param code_examples:

Code examples illustrating the recommendation

apifrom.performance.optimization.print_summary()

Print a summary of the recommendation to the console.

apifrom.performance.optimization.save(file_path)

Save the recommendation to a file.

param file_path:

The path to save the recommendation to

apifrom.performance.optimization.to_dict()

Convert the recommendation to a dictionary.

returns:

A dictionary representation of the recommendation

apifrom.performance.optimization.to_json(pretty=True)

Convert the recommendation to a JSON string.

param pretty:

Whether to format the JSON with indentation

returns:

A JSON string representation of the recommendation

class apifrom.performance.optimization.ProfileReport(endpoint_name, profile_data)[source]
Parameters:
  • endpoint_name (str)

  • profile_data (Dict[str, Any])

Represents a performance profile report for an API endpoint.

This class provides methods for analyzing and visualizing profile data, as well as exporting it to various formats.

Initialize a profile report.

param endpoint_name:

The name of the endpoint being profiled

param profile_data:

The raw profile data

class apifrom.performance.optimization.Request(request=None, path_params=None, method=None, path=None, query_params=None, headers=None, body=None, client_ip=None)[source]
Parameters:
  • request (Optional[starlette.requests.Request])

  • path_params (Optional[dict[Any, Any]])

  • method (Optional[str])

  • path (Optional[str])

  • query_params (Optional[dict[Any, Any]])

  • headers (Optional[dict[Any, Any]])

  • body (Optional[Union[str, bytes]])

  • client_ip (Optional[str])

Request class for APIFromAnything.

This class wraps a Starlette request and provides methods for accessing request data in a convenient way.

apifrom.performance.optimization._request

The underlying Starlette request.

apifrom.performance.optimization.path_params

Path parameters extracted from the URL.

apifrom.performance.optimization.query_params

Query parameters extracted from the URL.

apifrom.performance.optimization.headers

HTTP headers.

apifrom.performance.optimization.method

HTTP method.

apifrom.performance.optimization.path

Request path.

apifrom.performance.optimization._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.optimization.Response(content=None, status_code=200, headers=None, content_type='application/json')[source]
Parameters:
  • content (Any)

  • status_code (int)

  • headers (Optional[Dict[str, str]])

  • content_type (str)

Response class for APIFromAnything.

This class represents an HTTP response and provides methods for setting response data, status code, and headers.

apifrom.performance.optimization.content

The response content.

apifrom.performance.optimization.status_code

The HTTP status code.

apifrom.performance.optimization.headers

HTTP headers.

apifrom.performance.optimization.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.

class apifrom.performance.optimization.Web[source]

Decorator for optimizing web endpoints.

This decorator applies various optimizations to web endpoints, such as caching, profiling, and auto-tuning.

apifrom.performance.optimization.create_default_web_optimization()
:staticmethod:

Create a default web optimization decorator.

returns:

A default web optimization decorator with balanced settings

apifrom.performance.optimization.get_optimization_config(func)
:staticmethod:

Get the optimization configuration for a function.

param func:

The function to get the configuration for

returns:

The optimization configuration dictionary, or an empty dictionary if not optimized

apifrom.performance.optimization.is_optimized(func)
:staticmethod:

Check if a function is optimized.

param func:

The function to check

returns:

True if the function is optimized, False otherwise

apifrom.performance.optimization.optimize(cache_ttl=None, profile=True, connection_pool=True, auto_tune=True, request_coalescing=False, coalescing_ttl=30, batch_processing=False, batch_size=100, request_throttling=False, eager_loading=False, circuit_breaker=False)
:staticmethod:

Decorator for optimizing web endpoints.

param cache_ttl:

The cache TTL in seconds (None for no caching)

param profile:

Whether to profile the endpoint

param connection_pool:

Whether to use connection pooling

param auto_tune:

Whether to auto-tune the endpoint

param request_coalescing:

Whether to coalesce duplicate requests

param coalescing_ttl:

The time-to-live for coalesced requests in seconds

param batch_processing:

Whether to enable batch processing

param batch_size:

The maximum batch size for batch processing

param request_throttling:

Whether to throttle excessive requests

param eager_loading:

Whether to eagerly load related resources

param circuit_breaker:

Whether to use a circuit breaker

returns:

A decorated function