CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cloudinary

Python and Django SDK for Cloudinary, a cloud-based image and video management service with comprehensive transformation, optimization, and delivery capabilities

Overall
score

94%

Overview
Eval results
Files

transformations.mddocs/

URL Generation and Transformations

Powerful URL-based transformation system for images and videos with automatic optimization, responsive delivery, and format conversion.

Capabilities

URL Generation

Generate Cloudinary URLs with transformations and optimization parameters.

def cloudinary_url(public_id, **options):
    """Generate Cloudinary URL with transformations.
    
    Args:
        public_id (str): Public ID of the resource
        resource_type (str, optional): Type of resource ('image', 'video', 'raw')
        type (str, optional): Delivery type ('upload', 'private', 'authenticated', 'fetch', 'auto')
        version (str|int, optional): Version of the resource
        format (str, optional): Target format ('jpg', 'png', 'webp', 'auto', etc.)
        transformation (dict|list, optional): Transformation parameters
        secure (bool, optional): Use HTTPS (default: True)
        cdn_subdomain (bool, optional): Use CDN subdomain
        private_cdn (bool, optional): Use private CDN
        cname (str, optional): Custom domain name
        sign_url (bool, optional): Generate signed URL
        auth_token (dict, optional): Authentication token parameters
        
        # Image/Video Transformations:
        width (int, optional): Target width in pixels
        height (int, optional): Target height in pixels
        crop (str, optional): Crop mode ('scale', 'fit', 'limit', 'mfit', 'fill', 'lfill', 'pad', 'lpad', 'mpad', 'crop', 'thumb', 'imagga_crop', 'imagga_scale')
        aspect_ratio (str, optional): Target aspect ratio (e.g., '16:9', '1.5')
        gravity (str, optional): Crop gravity ('center', 'north', 'south', 'east', 'west', 'face', 'faces', 'auto', etc.)
        quality (str|int, optional): Quality setting (1-100 or 'auto', 'auto:good', 'auto:best', 'auto:eco', 'auto:low')
        fetch_format (str, optional): Automatic format selection ('auto', 'webp', 'avif')
        dpr (str|float, optional): Device pixel ratio ('auto' or number)
        flags (str|list, optional): Transformation flags
        
        # Image Effects and Filters:
        effect (str, optional): Visual effects
        color (str, optional): Color overlay
        background (str, optional): Background color or image
        border (str, optional): Border specification
        radius (str|int, optional): Corner radius ('max' for circle)
        angle (int, optional): Rotation angle
        opacity (int, optional): Opacity (0-100)
        overlay (str, optional): Image or text overlay
        underlay (str, optional): Image underlay
        
        # Video-specific:
        video_codec (str, optional): Video codec
        audio_codec (str, optional): Audio codec
        bit_rate (str, optional): Video bitrate
        audio_frequency (int, optional): Audio frequency
        video_sampling (int, optional): Video sampling
        start_offset (str, optional): Start time offset
        end_offset (str, optional): End time offset
        duration (str, optional): Video duration
        
        **kwargs: Additional transformation parameters
    
    Returns:
        tuple: (url, options_dict) where:
            - url (str): Generated Cloudinary URL
            - options_dict (dict): Processed options used for URL generation
    """

def cloudinary_tag(public_id, **options):
    """Generate HTML img tag with Cloudinary URL.
    
    Args:
        public_id (str): Public ID of the resource
        html_width (str|int, optional): HTML width attribute
        html_height (str|int, optional): HTML height attribute
        alt (str, optional): Alt text for accessibility
        title (str, optional): Title attribute
        class (str, optional): CSS class name
        id (str, optional): HTML id attribute
        responsive (bool, optional): Enable responsive image behavior
        responsive_breakpoints (list, optional): Custom responsive breakpoints
        client_hints (bool, optional): Enable client hints
        **options: Same transformation options as cloudinary_url()
    
    Returns:
        str: HTML img tag with Cloudinary URL and attributes
    """

def cloudinary_js_config():
    """Generate JavaScript configuration object for client-side usage.
    
    Returns:
        str: JavaScript code snippet with Cloudinary configuration
    """

Archive Generation

Create downloadable archives from multiple assets.

def create_archive_url(**options):
    """Generate URL for creating an archive from multiple assets.
    
    Args:
        public_ids (list, optional): Specific public IDs to include
        prefixes (list, optional): Public ID prefixes to include
        tags (list, optional): Tags to filter assets
        target_format (str, optional): Archive format ('zip', 'tgz')
        flatten_folders (bool, optional): Flatten folder structure in archive
        keep_derived (bool, optional): Include derived assets
        skip_transformation_name (bool, optional): Skip transformation names in paths
        allow_missing (bool, optional): Continue if some assets are missing
        expires_at (int, optional): Archive expiration timestamp
        resource_type (str, optional): Type of resources to include
        type (str, optional): Delivery type of resources
        mode (str, optional): Archive creation mode ('create', 'download')
        **kwargs: Additional archive options
    
    Returns:
        str: URL for archive creation/download
    """

def create_zip_url(**options):
    """Generate URL for creating a ZIP archive.
    
    Args:
        **options: Same options as create_archive_url() with target_format='zip'
    
    Returns:
        str: URL for ZIP archive creation/download
    """

Utility Functions

Helper functions for working with transformations and URLs.

def build_upload_url(**options):
    """Build URL for direct uploads from browsers.
    
    Args:
        resource_type (str, optional): Type of resource to upload
        **options: Upload configuration options
    
    Returns:
        str: Upload endpoint URL
    """

def finalize_upload_params(**options):
    """Process and finalize upload parameters.
    
    Args:
        **options: Upload parameters to process
    
    Returns:
        dict: Processed upload parameters
    """

def build_eager(transformations):
    """Build eager transformation list from transformation specifications.
    
    Args:
        transformations (list): List of transformation dictionaries
    
    Returns:
        list: Processed eager transformation list
    """

def normalize_expression(expression):
    """Normalize transformation expression syntax.
    
    Args:
        expression (str): Transformation expression
    
    Returns:
        str: Normalized expression
    """

def cloudinary_api_url(action='upload', **options):
    """Generate Cloudinary API endpoint URL.
    
    Args:
        action (str, optional): API action ('upload', 'destroy', 'rename', etc.)
        resource_type (str, optional): Type of resource ('image', 'video', 'raw')
        cloud_name (str, optional): Cloud name (defaults to config)
        upload_prefix (str, optional): Custom upload URL prefix
        **options: Additional URL options
    
    Returns:
        str: Complete API endpoint URL
    """

def base_api_url(path, **options):
    """Build base API URL with cloud name and version.
    
    Args:
        path (str|list): API path components
        cloud_name (str, optional): Cloud name (defaults to config)
        upload_prefix (str, optional): Custom upload URL prefix
        **options: Additional options
    
    Returns:
        str: Base API URL
    """

def private_download_url(public_id, format, **options):
    """Generate signed URL for downloading private assets.
    
    Args:
        public_id (str): Public ID of the asset
        format (str): File format to download
        type (str, optional): Asset type ('upload', 'private', etc.)
        attachment (bool, optional): Force download as attachment
        expires_at (int, optional): Expiration timestamp
        **options: Additional signature options
    
    Returns:
        str: Signed download URL
    """

def zip_download_url(tag, **options):
    """Generate URL for downloading assets with specific tag as ZIP.
    
    Args:
        tag (str): Tag to filter assets
        transformation (dict, optional): Transformation to apply to assets
        **options: Additional download options
    
    Returns:
        str: ZIP download URL
    """

def download_folder(folder_path, **options):
    """Generate URL for downloading entire folder as archive.
    
    Args:
        folder_path (str): Path of folder to download
        resource_type (str, optional): Type of resources ('image', 'video', 'raw', 'all')
        target_format (str, optional): Archive format ('zip', 'tgz')
        **options: Additional archive options
    
    Returns:
        str: Folder download URL
    """

def smart_escape(source, unsafe=r"([^a-zA-Z0-9_.\-\/:]+)"):
    """URL-encode unsafe characters in resource path.
    
    Args:
        source (str): Source string to escape
        unsafe (str, optional): Regex pattern for unsafe characters
    
    Returns:
        str: URL-escaped string
    """

def random_public_id():
    """Generate random public ID for asset uploads.
    
    Returns:
        str: Random 16-character alphanumeric public ID
    """

def signed_preloaded_image(result):
    """Generate signed path for preloaded image result.
    
    Args:
        result (dict): Upload result containing public_id, version, format, signature
    
    Returns:
        str: Signed path with format: path#signature
    """

def generate_auth_token(**options):
    """Generate authentication token for secure URLs.
    
    Args:
        key (str, optional): Authentication key
        duration (int, optional): Token validity duration in seconds
        start_time (int, optional): Token validity start time (timestamp)
        acl (str, optional): Access control list
        **options: Additional auth token options
    
    Returns:
        str: Generated authentication token
    """

Advanced Utilities

Advanced utility functions for data processing, encoding, and transformation handling.

def compute_hex_hash(s, algorithm='sha1'):
    """Compute hash string using specified algorithm.
    
    Args:
        s (str): String to compute hash for
        algorithm (str, optional): Hash algorithm ('sha1', 'sha256')
    
    Returns:
        str: Hexadecimal hash string
    """

def api_sign_request(params_to_sign, api_secret, algorithm='sha1', signature_version=2):
    """Sign API request parameters using specified algorithm and version.
    
    Args:
        params_to_sign (dict): Parameters to include in signature
        api_secret (str): API secret key
        algorithm (str, optional): Signature algorithm ('sha1', 'sha256')
        signature_version (int, optional): Signature version (1 or 2)
    
    Returns:
        str: Computed signature
    """

def verify_api_response_signature(public_id, version, signature, algorithm=None):
    """Verify authenticity of API response signature.
    
    Args:
        public_id (str): Public ID from API response
        version (str): Version from API response  
        signature (str): Signature to verify (from X-Cld-Signature header)
        algorithm (str, optional): Hash algorithm to use
    
    Returns:
        bool: True if signature is valid
    """

def verify_notification_signature(body, timestamp, signature, valid_for=7200, algorithm=None):
    """Verify authenticity of notification signature.
    
    Args:
        body (str): JSON request body
        timestamp (int): Unix timestamp (from X-Cld-Timestamp header)
        signature (str): Signature to verify (from X-Cld-Signature header)
        valid_for (int, optional): Validity period in seconds (default: 7200)
        algorithm (str, optional): Hash algorithm to use
    
    Returns:
        bool: True if signature is valid and within time window
    """

def build_array(arg):
    """Convert argument to array format.
    
    Args:
        arg: Value to convert (list, tuple, single value, or None)
    
    Returns:
        list: Converted array
    """

def build_list_of_dicts(val):
    """Convert value to list of dictionaries format.
    
    Args:
        val: Input value (dict, list, JSON string, or list of JSON strings)
    
    Returns:
        list: List of dictionaries
    
    Raises:
        ValueError: If value cannot be converted to list of dicts
    """

def encode_context(context):
    """Encode metadata context for API parameters.
    
    Args:
        context (dict): Context metadata to encode
    
    Returns:
        str: Pipe-separated encoded context string
    """

def encode_dict(arg):
    """Encode dictionary to pipe-separated key=value format.
    
    Args:
        arg (dict): Dictionary to encode
    
    Returns:
        str: Encoded string in format "key1=value1|key2=value2"
    """

def json_encode(value, sort_keys=False):
    """Convert value to JSON encoded string.
    
    Args:
        value: Value to encode
        sort_keys (bool, optional): Whether to sort dictionary keys
    
    Returns:
        str: JSON encoded string
    """

def base64_encode_url(url):
    """Encode URL in Base64 format.
    
    Args:
        url (str): URL to encode
    
    Returns:
        str: Base64 encoded URL
    """

def base64url_encode(data):
    """URL-safe Base64 encoding with padding removed.
    
    Args:
        data (str|bytes): Data to encode
    
    Returns:
        str: URL-safe Base64 encoded string
    """

def encode_list(obj):
    """Encode list to comma-separated string.
    
    Args:
        obj (list|str): List to encode or string to return as-is
    
    Returns:
        str: Comma-separated string
    """

def process_layer(layer, layer_parameter):
    """Process overlay/underlay layer specification.
    
    Args:
        layer (str|dict): Layer specification
        layer_parameter (str): Parameter name for error messages ('overlay' or 'underlay')
    
    Returns:
        str: Processed layer string for transformation
    """

def process_video_codec_param(param):
    """Process video codec parameter specification.
    
    Args:
        param (str|dict): Video codec specification
    
    Returns:
        str: Processed codec parameter string
    """

def process_fps(fps):
    """Process FPS (frames per second) parameter.
    
    Args:
        fps (int|float|str|list): FPS specification
    
    Returns:
        str: Processed FPS parameter
    """

def chain_transformations(options, transformations):
    """Chain transformations to existing options.
    
    Args:
        options (dict): Original transformation options
        transformations (list): Transformations to chain
    
    Returns:
        dict: Updated options with chained transformations
    """

def merge(*dict_args):
    """Merge multiple dictionaries into one.
    
    Args:
        *dict_args: Dictionaries to merge
    
    Returns:
        dict: Merged dictionary
    """

def html_attrs(attrs, only=None):
    """Generate HTML attribute string from dictionary.
    
    Args:
        attrs (dict): Attribute name-value pairs
        only (list, optional): Only include these attribute names
    
    Returns:
        str: Space-separated HTML attributes string
    """

def is_remote_url(file):
    """Check if string is a remote URL.
    
    Args:
        file (str): String to check
    
    Returns:
        bool: True if string matches remote URL pattern
    """

def file_io_size(file_io):
    """Get size of file-like object.
    
    Args:
        file_io: File-like object with seek/tell methods
    
    Returns:
        int: Size in bytes
    """

def safe_cast(val, casting_fn, default=None):
    """Safely cast value using casting function.
    
    Args:
        val: Value to cast
        casting_fn: Function to use for casting
        default: Default value if casting fails
    
    Returns:
        Casted value or default if casting fails
    """

def unique(collection, key=None):
    """Remove duplicates from collection.
    
    Args:
        collection: Iterable collection
        key (function, optional): Key function for comparison
    
    Returns:
        list: Collection with duplicates removed, preserving order
    """

def fq_public_id(public_id, resource_type="image", type="upload"):
    """Generate fully qualified public ID.
    
    Args:
        public_id (str): Public ID of the asset
        resource_type (str, optional): Resource type (default: 'image')
        type (str, optional): Upload type (default: 'upload')
    
    Returns:
        str: Fully qualified public ID in format "resource_type/type/public_id"
    """

def now():
    """Get current Unix timestamp as string.
    
    Returns:
        str: Current timestamp
    """

def build_upload_params(**options):
    """Build and process upload parameters.
    
    Args:
        **options: Upload options and parameters
    
    Returns:
        dict: Processed upload parameters ready for API submission
    """

def archive_params(**options):
    """Build parameters for archive creation.
    
    Args:
        public_ids (list, optional): Specific public IDs to include
        prefixes (list, optional): Public ID prefixes
        tags (list, optional): Tags to filter by
        target_format (str, optional): Archive format ('zip', 'tgz')
        **options: Additional archive options
    
    Returns:
        dict: Archive creation parameters
    """

def handle_file_parameter(file, filename=None):
    """Process file parameter for upload.
    
    Args:
        file: File to process (path, URL, stream, or bytes)
        filename (str, optional): Explicit filename
    
    Returns:
        tuple|str: Processed file data as (name, data) tuple or URL string
    """

def bracketize_seq(params):
    """Add brackets to parameter names for list values.
    
    Args:
        params (dict): Parameters to process
    
    Returns:
        dict: Parameters with "[]" appended to list parameter names
    """

def download_backedup_asset(asset_id, version_id, **options):
    """Generate URL for downloading backed up asset version.
    
    Args:
        asset_id (str): Asset ID from backup
        version_id (str): Version ID from backup
        timestamp (int, optional): Custom timestamp
        **options: Additional signature options
    
    Returns:
        str: Signed download URL for backed up asset
    """

def cloudinary_scaled_url(source, width, transformation, options):
    """Generate Cloudinary URL scaled to specified width.
    
    Args:
        source (str): The resource public ID
        width (int): Width in pixels for the scaled version
        transformation (str|dict, optional): Custom transformation to override options
        options (dict): Additional URL and transformation options
    
    Returns:
        str: URL of the scaled image
    """

def build_single_eager(options):
    """Build single eager transformation string.
    
    Args:
        options (str|dict): Transformation options or raw string
    
    Returns:
        str: Single eager transformation string with optional format
    """

def build_custom_headers(headers):
    """Build custom headers string for upload.
    
    Args:
        headers (dict|list|str): Headers specification
    
    Returns:
        str: Newline-separated headers string
    """

def build_multi_and_sprite_params(**options):
    """Build parameters for multi/sprite generation methods.
    
    Args:
        tag (str, optional): Tag to filter assets (mutually exclusive with urls)
        urls (list, optional): List of URLs (mutually exclusive with tag)
        mode (str, optional): Generation mode
        async (bool, optional): Asynchronous processing
        notification_url (str, optional): Webhook URL for completion
        format (str, optional): Target format
        **options: Additional transformation options
    
    Returns:
        dict: Parameters for multi/sprite operations
        
    Raises:
        ValueError: If both 'tag' and 'urls' are provided or neither is provided
    """

def cleanup_params(params):
    """Clean and normalize parameters for signature calculation.
    
    Args:
        params (dict): Parameters to clean
    
    Returns:
        dict: Cleaned parameters with None/empty values removed
    """

def normalize_params(params):
    """Normalize Admin API parameters.
    
    Args:
        params (dict): Parameters to normalize
    
    Returns:
        dict: Normalized parameters with boolean values as strings
    """

def generate_transformation_string(**options):
    """Generate transformation string from options.
    
    Args:
        **options: Transformation parameters
    
    Returns:
        tuple: (transformation_string, remaining_options)
    """

def patch_fetch_format(options):
    """Process fetch format options for fetch type uploads.
    
    Args:
        options (dict): Options to modify (modified in place)
    
    Note:
        This function modifies the options dictionary directly
    """

def encode_double_array(array):
    """Encode nested array to pipe and comma separated string.
    
    Args:
        array (list): Array to encode (may contain nested arrays)
    
    Returns:
        str: Encoded string with format "item1,item2|item3,item4"
    """

def normalize_context_value(value):
    """Normalize context value by escaping delimiters.
    
    Args:
        value: Value to normalize (int, str, list, or tuple)
    
    Returns:
        str: Normalized value with escaped = and | characters
    """

def encode_date_to_usage_api_format(date_obj):
    """Encode date object to usage API format.
    
    Args:
        date_obj (datetime.date): Date object to encode
    
    Returns:
        str: Date string in 'dd-mm-yyyy' format
    """

def process_radius(param):
    """Process radius parameter for rounded corners.
    
    Args:
        param (str|int|list|tuple): Radius specification
    
    Returns:
        str: Processed radius parameter
        
    Raises:
        ValueError: If radius param has invalid length (must be 1-4 values)
    """

def process_params(params):
    """Process parameters for API submission.
    
    Args:
        params (dict): Parameters to process
    
    Returns:
        dict: Processed parameters with array handling
    """

def breakpoint_settings_mapper(breakpoint_settings):
    """Map responsive breakpoint settings.
    
    Args:
        breakpoint_settings (dict): Breakpoint configuration
    
    Returns:
        dict: Mapped breakpoint settings with transformation string
    """

def generate_responsive_breakpoints_string(breakpoints):
    """Generate responsive breakpoints JSON string.
    
    Args:
        breakpoints (list): List of breakpoint configurations
    
    Returns:
        str: JSON string representation of breakpoints
    """

def finalize_source(source, format, url_suffix):
    """Finalize resource source with format and URL suffix.
    
    Args:
        source (str): Resource source identifier
        format (str): Resource format
        url_suffix (str): URL suffix to append
    
    Returns:
        tuple: (finalized_source, source_to_sign)
    """

def finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten):
    """Finalize resource type and upload type for URL generation.
    
    Args:
        resource_type (str): Resource type ('image', 'video', 'raw')
        type (str): Upload type ('upload', 'private', etc.)
        url_suffix (str): URL suffix
        use_root_path (bool): Whether to use root path
        shorten (bool): Whether to use shortened URLs
    
    Returns:
        tuple: (finalized_resource_type, finalized_type)
    """

def check_property_enabled(f):
    """Decorator to check if class property is enabled.
    
    Args:
        f (function): Function to wrap
    
    Returns:
        function: Wrapped function that checks self.enabled
    """

def get_http_connector(conf, options):
    """Create HTTP connector based on configuration.
    
    Args:
        conf: Configuration object
        options (dict): Additional connector options
    
    Returns:
        HTTP connector (PoolManager or ProxyManager)
    """

def process_custom_function(custom_function):
    """Process custom function parameter for transformations.
    
    Args:
        custom_function (str|dict): Custom function specification
    
    Returns:
        str: Processed custom function parameter
    """

def process_custom_pre_function(custom_function):
    """Process custom pre-function parameter for transformations.
    
    Args:
        custom_function (str|dict): Custom pre-function specification
    
    Returns:
        str: Processed custom pre-function parameter with 'pre:' prefix
    """

def process_conditional(conditional):
    """Process conditional transformation parameter.
    
    Args:
        conditional: Conditional expression
    
    Returns:
        str: Normalized conditional expression
    """

def encode_unicode_url(url_str):
    """Encode unicode URL string for safe transmission.
    
    Args:
        url_str (str): URL string to encode
    
    Returns:
        str: Encoded URL string
    """

def split_range(range):
    """Split range specification into start and end values.
    
    Args:
        range (str|list|tuple): Range specification (e.g., "10..20" or [10, 20])
    
    Returns:
        list|None: [start, end] values or None if invalid format
    """

def norm_range_value(value):
    """Normalize range value with percentage modifier.
    
    Args:
        value: Range value to normalize
    
    Returns:
        str|None: Normalized range value with 'p' modifier for percentages
    """

def norm_auto_range_value(value):
    """Normalize auto range value, preserving 'auto' keyword.
    
    Args:
        value: Range value to normalize (may be 'auto')
    
    Returns:
        str|None: Normalized range value or 'auto'
    """

def is_fraction(width):
    """Check if width value represents a fraction less than 1.
    
    Args:
        width: Width value to check
    
    Returns:
        bool: True if width is a decimal fraction less than 1
    """

def unsigned_download_url_prefix(source, cloud_name, private_cdn, cdn_subdomain, 
                                secure_cdn_subdomain, cname, secure, secure_distribution):
    """Generate URL prefix for unsigned downloads.
    
    Args:
        source (str): Resource source identifier
        cloud_name (str): Cloudinary cloud name
        private_cdn (bool): Whether using private CDN
        cdn_subdomain (bool): Whether to use CDN subdomains
        secure_cdn_subdomain (bool): Whether to use secure CDN subdomains
        cname (str): Custom domain name
        secure (bool): Whether to use HTTPS
        secure_distribution (str): Secure distribution domain
    
    Returns:
        str: URL prefix for resource downloads
    """

Usage Examples

Basic URL Generation

from cloudinary.utils import cloudinary_url

# Simple image URL
url, options = cloudinary_url("sample")
print(url)  # https://res.cloudinary.com/demo/image/upload/sample

# URL with basic transformations
url, options = cloudinary_url(
    "sample",
    width=300,
    height=200,
    crop="fill"
)

# HTTPS URL with format optimization
url, options = cloudinary_url(
    "sample",
    secure=True,
    quality="auto",
    format="auto"
)

Advanced Image Transformations

# Complex image transformation chain
url, options = cloudinary_url(
    "sample",
    transformation=[
        {"width": 1000, "height": 1000, "crop": "limit"},
        {"quality": "auto", "format": "auto"},
        {"effect": "sharpen", "radius": 3},
        {"border": "5px_solid_black"}
    ]
)

# Responsive image with automatic DPR
url, options = cloudinary_url(
    "sample",
    width=400,
    height=300,
    crop="fill",
    dpr="auto",
    responsive_breakpoints=[
        {"max_width": 1000, "max_images": 5},
        {"max_width": 500, "max_images": 3}
    ]
)

# Image with overlay and effects
url, options = cloudinary_url(
    "sample",
    width=500,
    height=500,
    crop="fill",
    overlay="text:Arial_60:Hello%20World",
    gravity="south",
    y=20,
    color="white",
    effect="shadow"
)

Video Transformations

# Video resizing and format conversion
url, options = cloudinary_url(
    "sample_video",
    resource_type="video",
    width=640,
    height=480,
    crop="pad",
    format="mp4",
    video_codec="h264",
    audio_codec="aac"
)

# Video with effects and trimming
url, options = cloudinary_url(
    "sample_video",
    resource_type="video",
    width=800,
    height=600,
    crop="fill",
    start_offset="10s",
    duration="30s",
    effect="sepia",
    quality="auto"
)

# Generate video thumbnail
url, options = cloudinary_url(
    "sample_video",
    resource_type="video",
    format="jpg",
    start_offset="50%",
    width=400,
    height=300,
    crop="fill"
)

HTML Tag Generation

from cloudinary.utils import cloudinary_tag

# Basic image tag
tag = cloudinary_tag(
    "sample",
    width=300,
    height=200,
    crop="fill",
    alt="Sample image"
)
print(tag)  # <img src="..." width="300" height="200" alt="Sample image">

# Responsive image tag
tag = cloudinary_tag(
    "sample",
    width=400,
    height=300,
    crop="fill",
    responsive=True,
    client_hints=True,
    class="responsive-image",
    alt="Responsive sample"
)

# Image with lazy loading
tag = cloudinary_tag(
    "sample",
    width=300,
    height=200,
    crop="fill",
    loading="lazy",
    class="lazy-image"
)

Archive Creation

from cloudinary.utils import create_archive_url, create_zip_url

# Create ZIP from specific images
zip_url = create_zip_url(
    public_ids=["image1", "image2", "image3"],
    target_format="zip"
)

# Create archive from tagged images
archive_url = create_archive_url(
    tags=["product"],
    target_format="tgz",
    resource_type="image",
    flatten_folders=True
)

# Create archive with transformations
archive_url = create_archive_url(
    prefixes=["products/"],
    transformations=[
        {"width": 800, "height": 600, "crop": "fit"}
    ],
    target_format="zip"
)

Advanced Features

# Signed URL for private resources
url, options = cloudinary_url(
    "private_image",
    type="private",
    sign_url=True,
    width=400,
    height=300
)

# Auto-optimization with Client Hints
url, options = cloudinary_url(
    "sample",
    width=400,
    height=300,
    crop="fill",
    dpr="auto",
    quality="auto",
    format="auto",
    fetch_format="auto"
)

# Progressive JPEG with quality analysis
url, options = cloudinary_url(
    "sample",
    width=800,
    height=600,
    quality="auto:good",
    flags="progressive",
    format="jpg"
)

# Image with face detection crop
url, options = cloudinary_url(
    "portrait",
    width=300,
    height=300,
    crop="thumb",
    gravity="face"
)

# Conditional transformations
url, options = cloudinary_url(
    "sample",
    transformation=[
        {"if": "w_gt_300", "width": 300, "height": 300, "crop": "scale"},
        {"if": "else", "width": 150, "height": 150, "crop": "scale"}
    ]
)

Resource-Specific URLs

# Fetch external image and transform
url, options = cloudinary_url(
    "https://example.com/image.jpg",
    type="fetch",
    width=400,
    height=300,
    crop="fill",
    quality="auto"
)

# Auto-upload from external URL
url, options = cloudinary_url(
    "https://example.com/image.jpg",
    type="auto",
    width=400,
    height=300,
    crop="fill"
)

# Private asset with authentication
url, options = cloudinary_url(
    "private_asset",
    type="authenticated",
    auth_token={
        "key": "your_auth_key",
        "duration": 3600,
        "start_time": 1234567890
    }
)

Utility Functions Usage

from cloudinary.utils import (
    private_download_url, generate_auth_token, smart_escape,
    random_public_id, signed_preloaded_image, build_array,
    encode_context, merge, fq_public_id, compute_hex_hash,
    verify_api_response_signature
)

# Generate private download URL
download_url = private_download_url(
    "my_private_image",
    "jpg",
    type="private",
    attachment=True,
    expires_at=1234567890
)

# Generate authentication token
auth_token = generate_auth_token(
    key="my_auth_key",
    duration=3600,
    acl="/image/*"
)

# URL encode special characters
escaped_path = smart_escape("path with spaces/special chars!")

# Generate random public ID
random_id = random_public_id()
print(random_id)  # e.g., "a3f2k8n9m1p4q7s2"

# Create signed preloaded image path
upload_result = {
    "public_id": "sample",
    "version": "1234567890",
    "format": "jpg",
    "signature": "abc123def456"
}
signed_path = signed_preloaded_image(upload_result)
print(signed_path)  # "image/upload/v1234567890/sample.jpg#abc123def456"

# Build array from various inputs
array1 = build_array("single_value")     # ["single_value"]
array2 = build_array(["a", "b", "c"])    # ["a", "b", "c"]
array3 = build_array(None)               # []

# Encode context metadata
context = {"key1": "value1", "key2": ["list", "value"]}
encoded = encode_context(context)
print(encoded)  # "key1=value1|key2=[\"list\",\"value\"]"

# Merge multiple dictionaries
options = merge(
    {"width": 400, "height": 300},
    {"crop": "fill", "quality": "auto"},
    {"format": "webp"}
)

# Generate fully qualified public ID
fq_id = fq_public_id("sample", "video", "upload")
print(fq_id)  # "video/upload/sample"

# Compute hash for signature verification
hash_value = compute_hex_hash("data_to_hash", "sha256")

# Verify API response signature
is_valid = verify_api_response_signature(
    public_id="sample",
    version="1234567890",
    signature="received_signature"
)

Advanced Processing Examples

from cloudinary.utils import (
    process_layer, chain_transformations, build_upload_params,
    archive_params, handle_file_parameter, json_encode,
    base64url_encode, unique, safe_cast
)

# Process overlay layer with text
text_overlay = process_layer({
    "text": "Hello World",
    "font_family": "Arial",
    "font_size": 40,
    "color": "white"
}, "overlay")

# Chain transformations
base_options = {"width": 400, "height": 300, "crop": "fill"}
additional_transforms = [
    {"effect": "sharpen"},
    {"border": "5px_solid_black"}
]
chained_options = chain_transformations(base_options, additional_transforms)

# Build upload parameters with metadata
upload_params = build_upload_params(
    public_id="sample_upload",
    tags=["product", "featured"],
    metadata={"category": "electronics", "price": 99.99},
    transformation={"width": 800, "height": 600, "crop": "fit"}
)

# Create archive parameters
archive_config = archive_params(
    tags=["product"],
    target_format="zip",
    flatten_folders=True,
    transformations=[{"width": 400, "height": 300, "crop": "fill"}]
)

# Handle different file types for upload
file_data1 = handle_file_parameter("/path/to/image.jpg")
file_data2 = handle_file_parameter("https://example.com/image.jpg")
file_data3 = handle_file_parameter(open("/path/to/image.jpg", "rb"))

# JSON encoding with custom serializer
data = {"timestamp": datetime.now(), "values": [1, 2, 3]}
json_string = json_encode(data)

# URL-safe Base64 encoding
encoded_data = base64url_encode("Hello, World!")

# Remove duplicates while preserving order
items = ["a", "b", "a", "c", "b", "d"]
unique_items = unique(items)
print(unique_items)  # ["a", "b", "c", "d"]

# Safe type casting with fallback
safe_int = safe_cast("123", int, 0)      # 123
safe_int_fail = safe_cast("abc", int, 0) # 0

Signature Verification Examples

from cloudinary.utils import (
    api_sign_request, verify_api_response_signature,
    verify_notification_signature, compute_hex_hash
)

# Sign API request parameters
params = {
    "public_id": "sample",
    "timestamp": "1234567890",
    "transformation": "w_400,h_300,c_fill"
}
signature = api_sign_request(
    params,
    api_secret="your_api_secret",
    algorithm="sha256",
    signature_version=2
)

# Verify webhook notification
webhook_body = '{"public_id":"sample","version":1234567890}'
timestamp = 1234567890
received_signature = "webhook_signature_from_header"

is_valid_notification = verify_notification_signature(
    body=webhook_body,
    timestamp=timestamp,
    signature=received_signature,
    valid_for=7200  # 2 hours
)

if is_valid_notification:
    print("Webhook notification is authentic")
else:
    print("Invalid or expired webhook notification")

# Manual hash computation for custom verification
data_to_hash = "sensitive_data" + "secret_key"
hash_result = compute_hex_hash(data_to_hash, "sha256")

Install with Tessl CLI

npx tessl i tessl/pypi-cloudinary

docs

admin-api.md

configuration.md

django-integration.md

exceptions.md

index.md

provisioning-api.md

search-api.md

transformations.md

upload-api.md

tile.json