Python and Django SDK for Cloudinary, a cloud-based image and video management service with comprehensive transformation, optimization, and delivery capabilities
Overall
score
94%
Complete configuration management for Cloudinary account credentials, default transformation parameters, and SDK behavior settings.
Configure Cloudinary account settings and default parameters that apply to all operations.
def config(**keywords):
"""Configure Cloudinary account settings and defaults.
Args:
cloud_name (str): Your Cloudinary cloud name (required)
api_key (str): Your API key (required for upload/admin operations)
api_secret (str): Your API secret (required for upload/admin operations)
secure (bool, optional): Use HTTPS URLs (default: True)
cdn_subdomain (bool, optional): Use multiple CDN subdomains for better performance
secure_cdn_subdomain (bool, optional): Use HTTPS CDN subdomains
private_cdn (bool, optional): Use private CDN distribution
cname (str, optional): Custom domain name for asset URLs
upload_prefix (str, optional): Custom upload URL prefix
api_proxy (str, optional): Proxy URL for API calls
auth_token (dict, optional): Default authentication token configuration
**kwargs: Additional configuration options
Returns:
Config: Configuration object with current settings
"""
def reset_config():
"""Reset configuration to default values.
Returns:
None
"""
def get_user_agent():
"""Get the current user agent string used for API requests.
Returns:
str: User agent string including platform information
"""Main configuration object that holds all Cloudinary settings.
class Config:
"""Configuration object for Cloudinary settings.
Attributes:
cloud_name (str): Cloudinary cloud name
api_key (str): API key for authenticated operations
api_secret (str): API secret for authenticated operations
secure (bool): Whether to use HTTPS URLs
cdn_subdomain (bool): Whether to use CDN subdomains
private_cdn (bool): Whether to use private CDN
cname (str): Custom domain name
auth_token (dict): Default authentication token settings
"""
def __init__(self, **options):
"""Initialize configuration with provided options."""
def __getattr__(self, key):
"""Get configuration value by attribute name."""
def __setattr__(self, key, value):
"""Set configuration value by attribute name."""Base classes for working with Cloudinary media assets.
class CloudinaryResource:
"""Base class for Cloudinary media resources.
Provides URL generation and transformation capabilities common to all resource types.
"""
def __init__(self, public_id=None, format=None, version=None, signature=None, **options):
"""Initialize a Cloudinary resource.
Args:
public_id (str, optional): Public identifier for the resource
format (str, optional): File format (jpg, png, webp, etc.)
version (str, optional): Version identifier
signature (str, optional): Signature for signed URLs
**options: Additional resource options
"""
def build_url(self, **options):
"""Build a URL for this resource with optional transformations.
Args:
**options: Transformation and URL generation options
Returns:
str: Generated Cloudinary URL
"""
def __unicode__(self):
"""Return string representation of the resource."""
def __str__(self):
"""Return string representation of the resource."""
class CloudinaryImage(CloudinaryResource):
"""Image-specific resource class with image transformation capabilities.
Extends CloudinaryResource with image-specific functionality and transformations.
"""
def image(self, **options):
"""Generate HTML img tag for this image.
Args:
**options: Image transformation and HTML attributes
Returns:
str: HTML img tag with Cloudinary URL
"""
class CloudinaryVideo(CloudinaryResource):
"""Video-specific resource class with video transformation capabilities.
Extends CloudinaryResource with video-specific functionality and transformations.
"""
def video(self, **options):
"""Generate HTML video tag for this video.
Args:
**options: Video transformation and HTML attributes
Returns:
str: HTML video tag with Cloudinary URL
"""import cloudinary
# Configure with account credentials
cloudinary.config(
cloud_name="demo",
api_key="123456789012345",
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx"
)
# Configure with additional options
cloudinary.config(
cloud_name="demo",
api_key="123456789012345",
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx",
secure=True,
cdn_subdomain=True,
private_cdn=False,
auth_token={
"key": "your_auth_key",
"duration": 3600
}
)import os
import cloudinary
# Set environment variables
os.environ['CLOUDINARY_URL'] = 'cloudinary://api_key:api_secret@cloud_name'
# Or configure individual components
os.environ['CLOUDINARY_CLOUD_NAME'] = 'demo'
os.environ['CLOUDINARY_API_KEY'] = '123456789012345'
os.environ['CLOUDINARY_API_SECRET'] = 'abcd_efgh_ijkl_mnop_qrst_uvwx'
# Import Django settings (if using Django)
cloudinary.import_django_settings()from cloudinary import CloudinaryImage, CloudinaryVideo
# Create image resource
image = CloudinaryImage("sample")
image_url = image.build_url(width=300, height=200, crop="fill")
# Create image with version and format
versioned_image = CloudinaryImage("sample", version=1234567890, format="jpg")
versioned_url = versioned_image.build_url(quality="auto")
# Create video resource
video = CloudinaryVideo("sample_video")
video_url = video.build_url(width=640, height=480, crop="pad")
# Generate HTML tags
img_tag = CloudinaryImage("sample").image(width=300, height=200, alt="Sample image")
video_tag = CloudinaryVideo("sample_video").video(width=640, height=480, controls=True)Generate and manage authentication tokens for secure URL access and API operations.
def generate(url=None, acl=None, start_time=None, duration=None,
expiration=None, ip=None, key=None, token_name="__cld_token__", **kwargs):
"""Generate an authentication token for secure Cloudinary URLs.
Args:
url (str, optional): Specific URL to authenticate (mutually exclusive with acl)
acl (str or list, optional): Access control list - URLs patterns to authenticate
start_time (int, optional): Token validity start time (Unix timestamp)
duration (int, optional): Token validity duration in seconds
expiration (int, optional): Token expiration time (Unix timestamp)
ip (str, optional): IP address restriction for token usage
key (str, optional): Secret key for HMAC signature generation
token_name (str, optional): Name for the token parameter (default: "__cld_token__")
**kwargs: Additional token parameters
Returns:
str: Generated authentication token string in format "token_name=token_value"
Raises:
Exception: If neither expiration nor duration is provided
Exception: If neither acl nor url is provided
"""
def generate_auth_token(**options):
"""Generate authentication token using configuration defaults.
Args:
**options: Token generation options (same as generate function)
Returns:
str: Generated authentication token string
"""
# Constants
AUTH_TOKEN_NAME = "__cld_token__"
AUTH_TOKEN_SEPARATOR = "~"import cloudinary
# Get current configuration
current_config = cloudinary.config()
print(f"Cloud name: {current_config.cloud_name}")
# Update specific settings
cloudinary.config(secure=True, cdn_subdomain=True)
# Reset to defaults
cloudinary.reset_config()
# Check user agent
user_agent = cloudinary.get_user_agent()
print(f"User agent: {user_agent}")from cloudinary import auth_token
import cloudinary
# Basic token generation with duration
token = auth_token.generate(
key="your_secret_key",
duration=3600, # 1 hour validity
acl="/image/upload/*" # Allow uploads to image/upload path
)
print(token) # "__cld_token__=ip=...~st=...~exp=...~acl=...~hmac=..."
# Token with specific URL and IP restriction
token = auth_token.generate(
key="your_secret_key",
url="/image/upload/sample.jpg",
ip="192.168.1.100",
expiration=1640995200 # Specific expiration timestamp
)
# Token for multiple ACL patterns
token = auth_token.generate(
key="your_secret_key",
duration=7200, # 2 hours
acl=["/image/*", "/video/*"], # Allow access to image and video paths
start_time=1640908800 # Custom start time
)
# Using configuration defaults
cloudinary.config(
cloud_name="demo",
api_key="123456789012345",
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx",
auth_token={
"key": "your_secret_key",
"duration": 3600
}
)
# Generate token using config defaults
from cloudinary.utils import generate_auth_token
token = generate_auth_token(acl="/image/private/*")
# Use token in URL generation
from cloudinary.utils import cloudinary_url
url, options = cloudinary_url(
"private_image",
type="authenticated",
auth_token={
"key": "your_secret_key",
"duration": 3600,
"acl": "/image/authenticated/*"
}
)Install with Tessl CLI
npx tessl i tessl/pypi-cloudinarydocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10