CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-webassets

Media asset management for Python, with glue code for various web frameworks

Overview
Eval results
Files

environment-configuration.mddocs/

Environment Configuration

Environment management for configuring asset processing, including directory paths, URL mapping, caching, version management, and bundle registration.

Capabilities

Environment Creation and Setup

Create and configure environments to manage asset processing settings and bundle collections.

class Environment:
    def __init__(self, directory=None, url=None, **more_config):
        """
        Create a new asset environment.
        
        Parameters:
        - directory: Base directory for asset files (filesystem path)
        - url: Base URL for serving assets (web path)
        - **more_config: Additional configuration options:
          - debug: Debug mode setting (bool)
          - cache: Cache configuration (str/bool/Cache instance)  
          - auto_build: Automatically build bundles when accessed (bool)
          - load_path: Additional search paths (list)
          - url_mapping: URL path mappings (dict)
          - versions: Versioning strategy (str/Version instance)
          - manifest: Manifest configuration (str/Manifest instance)
          - updater: Update checking strategy (str/Updater instance)
        """

Example usage:

from webassets import Environment

# Basic environment
env = Environment('./static', '/static')

# Environment with configuration
env = Environment(
    directory='./assets',
    url='/assets',
    debug=False,
    cache=True,
    auto_build=True,
    versions='hash'
)

# Environment with advanced settings
env = Environment(
    './static',
    '/static',
    load_path=['./vendor', './themes'],
    url_mapping={'/images': './img'},
    cache='filesystem',
    manifest='json:manifest.json'
)

Bundle Registration and Management

Register and manage bundles within the environment for organized asset processing.

def register(self, name, *args, **kwargs):
    """
    Register a bundle with the environment.
    
    Parameters:
    - name: Bundle name for later reference
    - *args: Bundle arguments (files, nested bundles)
    - **kwargs: Bundle options (filters, output, etc.)
    
    Returns:
    The created Bundle instance
    """

def add(self, *bundles):
    """
    Add anonymous bundles to the environment.
    
    Parameters:
    - *bundles: Bundle instances to add
    """

def append_path(self, path, url=None):
    """
    Add a directory to the load path.
    
    Parameters:
    - path: Directory path to add
    - url: Optional URL mapping for the path
    """

Example usage:

# Register named bundles
js_bundle = env.register('js_all',
    'jquery.js',
    'app.js',
    filters='jsmin',
    output='gen/app.js'
)

css_bundle = env.register('css_all',
    'style.css',
    'layout.css', 
    filters='cssmin',
    output='gen/style.css'
)

# Add anonymous bundles
from webassets import Bundle
vendor_bundle = Bundle('vendor/lib.js', output='gen/vendor.js')
env.add(vendor_bundle)

# Add to load path
env.append_path('./vendor')
env.append_path('./themes', '/themes')

# Access registered bundles
js_urls = env['js_all'].urls()
css_urls = env['css_all'].urls()

Bundle Registry

Registry for managing named and anonymous bundles within an environment.

class BundleRegistry:
    def register(self, name, *args, **kwargs):
        """Register a bundle with a name."""
    
    def add(self, *bundles):
        """Add anonymous bundles."""
    
    def __getitem__(self, name):
        """Get bundle by name."""
    
    def __contains__(self, name):
        """Check if bundle exists."""
    
    def __iter__(self):
        """Iterate over all bundles."""
    
    def __len__(self):
        """Get total number of registered bundles."""
    
    def __bool__(self):
        """Check if registry contains any bundles."""
    
    def decompose_bundle(self, name, bundle):
        """Decompose bundle with merge=False into individual file bundles."""
    
    def register_decomposed(self, name, bundle, abspath):
        """Register single decomposed bundle for specific file."""

Path and URL Resolution

Resolve file paths and URLs for assets within the environment configuration.

class Resolver:
    def search_for_source(self, ctx, item):
        """
        Find source file in load paths.
        
        Parameters:
        - ctx: Search context
        - item: File or pattern to find
        
        Returns:
        Found file path or None
        """
    
    def resolve_source(self, ctx, item):
        """
        Resolve source to filesystem path.
        
        Parameters:
        - ctx: Resolution context
        - item: Source specification
        
        Returns:
        Absolute filesystem path
        """
    
    def resolve_source_to_url(self, ctx, filepath, item):
        """
        Resolve source to web URL.
        
        Parameters:
        - ctx: Resolution context
        - filepath: Source file path
        - item: Source item
        
        Returns:
        Web-accessible URL
        """
    
    def resolve_output_to_path(self, ctx, target, bundle):
        """
        Resolve output to filesystem path.
        
        Parameters:
        - ctx: Resolution context
        - target: Output target
        - bundle: Source bundle
        
        Returns:
        Output filesystem path
        """
    
    def resolve_output_to_url(self, ctx, target):
        """
        Resolve output to web URL.
        
        Parameters:
        - ctx: Resolution context
        - target: Output target
        
        Returns:
        Output web URL
        """
    
    def glob(self, basedir, expr):
        """
        Evaluate glob expression and return sorted absolute filenames.
        
        Parameters:
        - basedir: Base directory for glob evaluation
        - expr: Glob expression pattern
        
        Returns:
        Sorted list of absolute filenames matching pattern
        """
    
    def consider_single_directory(self, directory, item):
        """
        Search for item within specific directory, handling glob patterns.
        
        Parameters:
        - directory: Directory to search in
        - item: File or pattern to find
        
        Returns:
        File path or list of paths if glob pattern
        """
    
    def search_env_directory(self, ctx, item):
        """
        Search for source in environment's base directory.
        
        Parameters:
        - ctx: Resolution context
        - item: Source item to find
        
        Returns:
        Found file path or list of paths
        """
    
    def search_load_path(self, ctx, item):
        """
        Search for source files in configured load paths.
        
        Parameters:
        - ctx: Resolution context with load_path
        - item: Source item to find
        
        Returns:
        Found file path or None if not found
        """
    
    def search_for_source(self, ctx, item):
        """
        Perform comprehensive search for source item.
        
        Parameters:
        - ctx: Resolution context
        - item: Source item to find
        
        Returns:
        Found file path(s) or raises error if not found
        """
    
    def query_url_mapping(self, ctx, item):
        """
        Query URL mapping configuration for source item.
        
        Parameters:
        - ctx: Resolution context with url_mapping
        - item: Source item to look up
        
        Returns:
        Mapped URL or None if no mapping found
        """
    
    def query_url_mapping(self, ctx, filepath):
        """
        Find correct URL for filesystem path using URL mappings.
        
        Parameters:
        - ctx: Resolution context
        - filepath: Absolute filesystem path
        
        Returns:
        Web-accessible URL for the file
        """

Bundle Registry

Registry for managing bundle collections with decomposition support for merge=False bundles.

class BundleRegistry:
    def __init__(self, env):
        """Initialize bundle registry for environment."""
    
    def __len__(self):
        """Return number of registered bundles."""
    
    def __bool__(self):
        """Return True if registry contains bundles."""
    
    def __getitem__(self, name):
        """Get bundle by name."""
    
    def __setitem__(self, name, bundle):
        """Register bundle with name."""
    
    def __delitem__(self, name):
        """Remove bundle from registry."""
    
    def __contains__(self, name):
        """Check if bundle name is registered."""
    
    def __iter__(self):
        """Iterate over bundle names."""
    
    def decompose_bundle(self, bundle):
        """
        Handle bundles with merge=False by decomposing into individual files.
        
        Parameters:
        - bundle: Bundle to decompose
        
        Returns:
        List of individual file bundles or original bundle
        """
    
    def register_decomposed(self, name, bundle):
        """
        Register bundle with decomposition handling.
        
        Parameters:
        - name: Bundle name
        - bundle: Bundle to register (may be decomposed)
        """

Configuration Storage

Backend for environment configuration with case-insensitive key handling.

class ConfigStorage:
    def __init__(self, env):
        """Initialize configuration storage for environment."""
    
    def get(self, key, default=None):
        """Get configuration value with default."""
    
    def __getitem__(self, key):
        """Get configuration value."""
    
    def __setitem__(self, key, value):
        """Set configuration value."""
    
    def __delitem__(self, key):
        """Delete configuration value."""
    
    def __contains__(self, key):
        """Check if configuration key exists."""
    
    def update(self, d):
        """Update configuration with values from dictionary."""
    
    def setdefault(self, key, value):
        """Set configuration key to value if key doesn't exist."""

Environment Properties

Access environment configuration and state through properties.

# Core properties
@property
def directory(self):
    """Asset base directory"""

@property  
def url(self):
    """Asset base URL"""

@property
def debug(self):
    """Debug mode setting"""

@property
def cache(self):
    """Caching configuration"""

@property
def auto_build(self):
    """Automatic building setting"""

@property
def load_path(self):
    """Additional search paths"""

@property
def url_mapping(self):
    """URL path mappings"""

@property
def resolver(self):
    """Path resolver instance"""

@property
def updater(self):
    """Update checker instance"""

@property
def versions(self):
    """Versioning configuration"""

@property
def manifest(self):
    """Manifest configuration"""

@property
def cache_file_mode(self):
    """File permissions for cached files (octal)"""

@property
def url_expire(self):
    """URL expiration setting for cache headers"""

@property
def config(self):
    """Configuration storage instance"""

@property
def cache_file_mode(self):
    """Cache file creation mode (octal)"""

Utility Functions

Helper functions for configuration value parsing and validation.

def parse_debug_value(value):
    """
    Parse string value to debug option setting.
    
    Parameters:
    - value: String value to parse ('true', 'false', 'merge', etc.)
    
    Returns:
    Parsed debug setting (bool or string)
    """

Example usage:

# Parse debug values
debug_setting = parse_debug_value('merge')  # Returns 'merge'
debug_setting = parse_debug_value('true')   # Returns True
debug_setting = parse_debug_value('false')  # Returns False

Advanced Configuration Examples

Multi-Environment Setup

# Development environment
dev_env = Environment(
    './src/assets',
    '/static',
    debug=True,
    auto_build=True,
    cache=False
)

# Production environment  
prod_env = Environment(
    './static',
    '/static',
    debug=False,
    cache='filesystem',
    versions='hash',
    manifest='json:manifest.json'
)

# Register same bundles in both
for env in [dev_env, prod_env]:
    env.register('js_app',
        'app.js',
        'utils.js',
        filters='jsmin' if not env.debug else None,
        output='gen/app.js'
    )

Complex Path Configuration

env = Environment('./static', '/static')

# Add multiple search paths
env.append_path('./vendor/css', '/vendor/css')
env.append_path('./themes', '/themes')
env.append_path('./node_modules', '/npm')

# URL mappings for different asset types
env.url_mapping = {
    '/images': './img',
    '/fonts': './fonts',
    '/icons': './icons'
}

Dynamic Environment Configuration

def create_environment(mode='development'):
    config = {
        'directory': './static',
        'url': '/static',
        'debug': mode == 'development',
        'auto_build': mode == 'development',
        'cache': mode != 'development'
    }
    
    if mode == 'production':
        config.update({
            'versions': 'hash',
            'manifest': 'json:assets.json'
        })
    
    return Environment(**config)

# Create environment based on mode
env = create_environment('production')

Framework Integration Patterns

# Flask integration example
def create_flask_assets(app):
    env = Environment(
        directory=app.static_folder,
        url=app.static_url_path,
        debug=app.debug,
        auto_build=app.debug
    )
    
    # Register common bundles
    env.register('js_vendor',
        'vendor/jquery.js',
        'vendor/bootstrap.js',
        filters='jsmin',
        output='gen/vendor.js'
    )
    
    return env

Install with Tessl CLI

npx tessl i tessl/pypi-webassets

docs

bundle-management.md

caching-versioning.md

command-line.md

configuration-loading.md

environment-configuration.md

filter-system.md

framework-integration.md

index.md

merge-system.md

updater-system.md

utilities.md

tile.json