0
# URL Generation and Transformations
1
2
Powerful URL-based transformation system for images and videos with automatic optimization, responsive delivery, and format conversion.
3
4
## Capabilities
5
6
### URL Generation
7
8
Generate Cloudinary URLs with transformations and optimization parameters.
9
10
```python { .api }
11
def cloudinary_url(public_id, **options):
12
"""Generate Cloudinary URL with transformations.
13
14
Args:
15
public_id (str): Public ID of the resource
16
resource_type (str, optional): Type of resource ('image', 'video', 'raw')
17
type (str, optional): Delivery type ('upload', 'private', 'authenticated', 'fetch', 'auto')
18
version (str|int, optional): Version of the resource
19
format (str, optional): Target format ('jpg', 'png', 'webp', 'auto', etc.)
20
transformation (dict|list, optional): Transformation parameters
21
secure (bool, optional): Use HTTPS (default: True)
22
cdn_subdomain (bool, optional): Use CDN subdomain
23
private_cdn (bool, optional): Use private CDN
24
cname (str, optional): Custom domain name
25
sign_url (bool, optional): Generate signed URL
26
auth_token (dict, optional): Authentication token parameters
27
28
# Image/Video Transformations:
29
width (int, optional): Target width in pixels
30
height (int, optional): Target height in pixels
31
crop (str, optional): Crop mode ('scale', 'fit', 'limit', 'mfit', 'fill', 'lfill', 'pad', 'lpad', 'mpad', 'crop', 'thumb', 'imagga_crop', 'imagga_scale')
32
aspect_ratio (str, optional): Target aspect ratio (e.g., '16:9', '1.5')
33
gravity (str, optional): Crop gravity ('center', 'north', 'south', 'east', 'west', 'face', 'faces', 'auto', etc.)
34
quality (str|int, optional): Quality setting (1-100 or 'auto', 'auto:good', 'auto:best', 'auto:eco', 'auto:low')
35
fetch_format (str, optional): Automatic format selection ('auto', 'webp', 'avif')
36
dpr (str|float, optional): Device pixel ratio ('auto' or number)
37
flags (str|list, optional): Transformation flags
38
39
# Image Effects and Filters:
40
effect (str, optional): Visual effects
41
color (str, optional): Color overlay
42
background (str, optional): Background color or image
43
border (str, optional): Border specification
44
radius (str|int, optional): Corner radius ('max' for circle)
45
angle (int, optional): Rotation angle
46
opacity (int, optional): Opacity (0-100)
47
overlay (str, optional): Image or text overlay
48
underlay (str, optional): Image underlay
49
50
# Video-specific:
51
video_codec (str, optional): Video codec
52
audio_codec (str, optional): Audio codec
53
bit_rate (str, optional): Video bitrate
54
audio_frequency (int, optional): Audio frequency
55
video_sampling (int, optional): Video sampling
56
start_offset (str, optional): Start time offset
57
end_offset (str, optional): End time offset
58
duration (str, optional): Video duration
59
60
**kwargs: Additional transformation parameters
61
62
Returns:
63
tuple: (url, options_dict) where:
64
- url (str): Generated Cloudinary URL
65
- options_dict (dict): Processed options used for URL generation
66
"""
67
68
def cloudinary_tag(public_id, **options):
69
"""Generate HTML img tag with Cloudinary URL.
70
71
Args:
72
public_id (str): Public ID of the resource
73
html_width (str|int, optional): HTML width attribute
74
html_height (str|int, optional): HTML height attribute
75
alt (str, optional): Alt text for accessibility
76
title (str, optional): Title attribute
77
class (str, optional): CSS class name
78
id (str, optional): HTML id attribute
79
responsive (bool, optional): Enable responsive image behavior
80
responsive_breakpoints (list, optional): Custom responsive breakpoints
81
client_hints (bool, optional): Enable client hints
82
**options: Same transformation options as cloudinary_url()
83
84
Returns:
85
str: HTML img tag with Cloudinary URL and attributes
86
"""
87
88
def cloudinary_js_config():
89
"""Generate JavaScript configuration object for client-side usage.
90
91
Returns:
92
str: JavaScript code snippet with Cloudinary configuration
93
"""
94
```
95
96
### Archive Generation
97
98
Create downloadable archives from multiple assets.
99
100
```python { .api }
101
def create_archive_url(**options):
102
"""Generate URL for creating an archive from multiple assets.
103
104
Args:
105
public_ids (list, optional): Specific public IDs to include
106
prefixes (list, optional): Public ID prefixes to include
107
tags (list, optional): Tags to filter assets
108
target_format (str, optional): Archive format ('zip', 'tgz')
109
flatten_folders (bool, optional): Flatten folder structure in archive
110
keep_derived (bool, optional): Include derived assets
111
skip_transformation_name (bool, optional): Skip transformation names in paths
112
allow_missing (bool, optional): Continue if some assets are missing
113
expires_at (int, optional): Archive expiration timestamp
114
resource_type (str, optional): Type of resources to include
115
type (str, optional): Delivery type of resources
116
mode (str, optional): Archive creation mode ('create', 'download')
117
**kwargs: Additional archive options
118
119
Returns:
120
str: URL for archive creation/download
121
"""
122
123
def create_zip_url(**options):
124
"""Generate URL for creating a ZIP archive.
125
126
Args:
127
**options: Same options as create_archive_url() with target_format='zip'
128
129
Returns:
130
str: URL for ZIP archive creation/download
131
"""
132
```
133
134
### Utility Functions
135
136
Helper functions for working with transformations and URLs.
137
138
```python { .api }
139
def build_upload_url(**options):
140
"""Build URL for direct uploads from browsers.
141
142
Args:
143
resource_type (str, optional): Type of resource to upload
144
**options: Upload configuration options
145
146
Returns:
147
str: Upload endpoint URL
148
"""
149
150
def finalize_upload_params(**options):
151
"""Process and finalize upload parameters.
152
153
Args:
154
**options: Upload parameters to process
155
156
Returns:
157
dict: Processed upload parameters
158
"""
159
160
def build_eager(transformations):
161
"""Build eager transformation list from transformation specifications.
162
163
Args:
164
transformations (list): List of transformation dictionaries
165
166
Returns:
167
list: Processed eager transformation list
168
"""
169
170
def normalize_expression(expression):
171
"""Normalize transformation expression syntax.
172
173
Args:
174
expression (str): Transformation expression
175
176
Returns:
177
str: Normalized expression
178
"""
179
180
def cloudinary_api_url(action='upload', **options):
181
"""Generate Cloudinary API endpoint URL.
182
183
Args:
184
action (str, optional): API action ('upload', 'destroy', 'rename', etc.)
185
resource_type (str, optional): Type of resource ('image', 'video', 'raw')
186
cloud_name (str, optional): Cloud name (defaults to config)
187
upload_prefix (str, optional): Custom upload URL prefix
188
**options: Additional URL options
189
190
Returns:
191
str: Complete API endpoint URL
192
"""
193
194
def base_api_url(path, **options):
195
"""Build base API URL with cloud name and version.
196
197
Args:
198
path (str|list): API path components
199
cloud_name (str, optional): Cloud name (defaults to config)
200
upload_prefix (str, optional): Custom upload URL prefix
201
**options: Additional options
202
203
Returns:
204
str: Base API URL
205
"""
206
207
def private_download_url(public_id, format, **options):
208
"""Generate signed URL for downloading private assets.
209
210
Args:
211
public_id (str): Public ID of the asset
212
format (str): File format to download
213
type (str, optional): Asset type ('upload', 'private', etc.)
214
attachment (bool, optional): Force download as attachment
215
expires_at (int, optional): Expiration timestamp
216
**options: Additional signature options
217
218
Returns:
219
str: Signed download URL
220
"""
221
222
def zip_download_url(tag, **options):
223
"""Generate URL for downloading assets with specific tag as ZIP.
224
225
Args:
226
tag (str): Tag to filter assets
227
transformation (dict, optional): Transformation to apply to assets
228
**options: Additional download options
229
230
Returns:
231
str: ZIP download URL
232
"""
233
234
def download_folder(folder_path, **options):
235
"""Generate URL for downloading entire folder as archive.
236
237
Args:
238
folder_path (str): Path of folder to download
239
resource_type (str, optional): Type of resources ('image', 'video', 'raw', 'all')
240
target_format (str, optional): Archive format ('zip', 'tgz')
241
**options: Additional archive options
242
243
Returns:
244
str: Folder download URL
245
"""
246
247
def smart_escape(source, unsafe=r"([^a-zA-Z0-9_.\-\/:]+)"):
248
"""URL-encode unsafe characters in resource path.
249
250
Args:
251
source (str): Source string to escape
252
unsafe (str, optional): Regex pattern for unsafe characters
253
254
Returns:
255
str: URL-escaped string
256
"""
257
258
def random_public_id():
259
"""Generate random public ID for asset uploads.
260
261
Returns:
262
str: Random 16-character alphanumeric public ID
263
"""
264
265
def signed_preloaded_image(result):
266
"""Generate signed path for preloaded image result.
267
268
Args:
269
result (dict): Upload result containing public_id, version, format, signature
270
271
Returns:
272
str: Signed path with format: path#signature
273
"""
274
275
def generate_auth_token(**options):
276
"""Generate authentication token for secure URLs.
277
278
Args:
279
key (str, optional): Authentication key
280
duration (int, optional): Token validity duration in seconds
281
start_time (int, optional): Token validity start time (timestamp)
282
acl (str, optional): Access control list
283
**options: Additional auth token options
284
285
Returns:
286
str: Generated authentication token
287
"""
288
```
289
290
### Advanced Utilities
291
292
Advanced utility functions for data processing, encoding, and transformation handling.
293
294
```python { .api }
295
def compute_hex_hash(s, algorithm='sha1'):
296
"""Compute hash string using specified algorithm.
297
298
Args:
299
s (str): String to compute hash for
300
algorithm (str, optional): Hash algorithm ('sha1', 'sha256')
301
302
Returns:
303
str: Hexadecimal hash string
304
"""
305
306
def api_sign_request(params_to_sign, api_secret, algorithm='sha1', signature_version=2):
307
"""Sign API request parameters using specified algorithm and version.
308
309
Args:
310
params_to_sign (dict): Parameters to include in signature
311
api_secret (str): API secret key
312
algorithm (str, optional): Signature algorithm ('sha1', 'sha256')
313
signature_version (int, optional): Signature version (1 or 2)
314
315
Returns:
316
str: Computed signature
317
"""
318
319
def verify_api_response_signature(public_id, version, signature, algorithm=None):
320
"""Verify authenticity of API response signature.
321
322
Args:
323
public_id (str): Public ID from API response
324
version (str): Version from API response
325
signature (str): Signature to verify (from X-Cld-Signature header)
326
algorithm (str, optional): Hash algorithm to use
327
328
Returns:
329
bool: True if signature is valid
330
"""
331
332
def verify_notification_signature(body, timestamp, signature, valid_for=7200, algorithm=None):
333
"""Verify authenticity of notification signature.
334
335
Args:
336
body (str): JSON request body
337
timestamp (int): Unix timestamp (from X-Cld-Timestamp header)
338
signature (str): Signature to verify (from X-Cld-Signature header)
339
valid_for (int, optional): Validity period in seconds (default: 7200)
340
algorithm (str, optional): Hash algorithm to use
341
342
Returns:
343
bool: True if signature is valid and within time window
344
"""
345
346
def build_array(arg):
347
"""Convert argument to array format.
348
349
Args:
350
arg: Value to convert (list, tuple, single value, or None)
351
352
Returns:
353
list: Converted array
354
"""
355
356
def build_list_of_dicts(val):
357
"""Convert value to list of dictionaries format.
358
359
Args:
360
val: Input value (dict, list, JSON string, or list of JSON strings)
361
362
Returns:
363
list: List of dictionaries
364
365
Raises:
366
ValueError: If value cannot be converted to list of dicts
367
"""
368
369
def encode_context(context):
370
"""Encode metadata context for API parameters.
371
372
Args:
373
context (dict): Context metadata to encode
374
375
Returns:
376
str: Pipe-separated encoded context string
377
"""
378
379
def encode_dict(arg):
380
"""Encode dictionary to pipe-separated key=value format.
381
382
Args:
383
arg (dict): Dictionary to encode
384
385
Returns:
386
str: Encoded string in format "key1=value1|key2=value2"
387
"""
388
389
def json_encode(value, sort_keys=False):
390
"""Convert value to JSON encoded string.
391
392
Args:
393
value: Value to encode
394
sort_keys (bool, optional): Whether to sort dictionary keys
395
396
Returns:
397
str: JSON encoded string
398
"""
399
400
def base64_encode_url(url):
401
"""Encode URL in Base64 format.
402
403
Args:
404
url (str): URL to encode
405
406
Returns:
407
str: Base64 encoded URL
408
"""
409
410
def base64url_encode(data):
411
"""URL-safe Base64 encoding with padding removed.
412
413
Args:
414
data (str|bytes): Data to encode
415
416
Returns:
417
str: URL-safe Base64 encoded string
418
"""
419
420
def encode_list(obj):
421
"""Encode list to comma-separated string.
422
423
Args:
424
obj (list|str): List to encode or string to return as-is
425
426
Returns:
427
str: Comma-separated string
428
"""
429
430
def process_layer(layer, layer_parameter):
431
"""Process overlay/underlay layer specification.
432
433
Args:
434
layer (str|dict): Layer specification
435
layer_parameter (str): Parameter name for error messages ('overlay' or 'underlay')
436
437
Returns:
438
str: Processed layer string for transformation
439
"""
440
441
def process_video_codec_param(param):
442
"""Process video codec parameter specification.
443
444
Args:
445
param (str|dict): Video codec specification
446
447
Returns:
448
str: Processed codec parameter string
449
"""
450
451
def process_fps(fps):
452
"""Process FPS (frames per second) parameter.
453
454
Args:
455
fps (int|float|str|list): FPS specification
456
457
Returns:
458
str: Processed FPS parameter
459
"""
460
461
def chain_transformations(options, transformations):
462
"""Chain transformations to existing options.
463
464
Args:
465
options (dict): Original transformation options
466
transformations (list): Transformations to chain
467
468
Returns:
469
dict: Updated options with chained transformations
470
"""
471
472
def merge(*dict_args):
473
"""Merge multiple dictionaries into one.
474
475
Args:
476
*dict_args: Dictionaries to merge
477
478
Returns:
479
dict: Merged dictionary
480
"""
481
482
def html_attrs(attrs, only=None):
483
"""Generate HTML attribute string from dictionary.
484
485
Args:
486
attrs (dict): Attribute name-value pairs
487
only (list, optional): Only include these attribute names
488
489
Returns:
490
str: Space-separated HTML attributes string
491
"""
492
493
def is_remote_url(file):
494
"""Check if string is a remote URL.
495
496
Args:
497
file (str): String to check
498
499
Returns:
500
bool: True if string matches remote URL pattern
501
"""
502
503
def file_io_size(file_io):
504
"""Get size of file-like object.
505
506
Args:
507
file_io: File-like object with seek/tell methods
508
509
Returns:
510
int: Size in bytes
511
"""
512
513
def safe_cast(val, casting_fn, default=None):
514
"""Safely cast value using casting function.
515
516
Args:
517
val: Value to cast
518
casting_fn: Function to use for casting
519
default: Default value if casting fails
520
521
Returns:
522
Casted value or default if casting fails
523
"""
524
525
def unique(collection, key=None):
526
"""Remove duplicates from collection.
527
528
Args:
529
collection: Iterable collection
530
key (function, optional): Key function for comparison
531
532
Returns:
533
list: Collection with duplicates removed, preserving order
534
"""
535
536
def fq_public_id(public_id, resource_type="image", type="upload"):
537
"""Generate fully qualified public ID.
538
539
Args:
540
public_id (str): Public ID of the asset
541
resource_type (str, optional): Resource type (default: 'image')
542
type (str, optional): Upload type (default: 'upload')
543
544
Returns:
545
str: Fully qualified public ID in format "resource_type/type/public_id"
546
"""
547
548
def now():
549
"""Get current Unix timestamp as string.
550
551
Returns:
552
str: Current timestamp
553
"""
554
555
def build_upload_params(**options):
556
"""Build and process upload parameters.
557
558
Args:
559
**options: Upload options and parameters
560
561
Returns:
562
dict: Processed upload parameters ready for API submission
563
"""
564
565
def archive_params(**options):
566
"""Build parameters for archive creation.
567
568
Args:
569
public_ids (list, optional): Specific public IDs to include
570
prefixes (list, optional): Public ID prefixes
571
tags (list, optional): Tags to filter by
572
target_format (str, optional): Archive format ('zip', 'tgz')
573
**options: Additional archive options
574
575
Returns:
576
dict: Archive creation parameters
577
"""
578
579
def handle_file_parameter(file, filename=None):
580
"""Process file parameter for upload.
581
582
Args:
583
file: File to process (path, URL, stream, or bytes)
584
filename (str, optional): Explicit filename
585
586
Returns:
587
tuple|str: Processed file data as (name, data) tuple or URL string
588
"""
589
590
def bracketize_seq(params):
591
"""Add brackets to parameter names for list values.
592
593
Args:
594
params (dict): Parameters to process
595
596
Returns:
597
dict: Parameters with "[]" appended to list parameter names
598
"""
599
600
def download_backedup_asset(asset_id, version_id, **options):
601
"""Generate URL for downloading backed up asset version.
602
603
Args:
604
asset_id (str): Asset ID from backup
605
version_id (str): Version ID from backup
606
timestamp (int, optional): Custom timestamp
607
**options: Additional signature options
608
609
Returns:
610
str: Signed download URL for backed up asset
611
"""
612
613
def cloudinary_scaled_url(source, width, transformation, options):
614
"""Generate Cloudinary URL scaled to specified width.
615
616
Args:
617
source (str): The resource public ID
618
width (int): Width in pixels for the scaled version
619
transformation (str|dict, optional): Custom transformation to override options
620
options (dict): Additional URL and transformation options
621
622
Returns:
623
str: URL of the scaled image
624
"""
625
626
def build_single_eager(options):
627
"""Build single eager transformation string.
628
629
Args:
630
options (str|dict): Transformation options or raw string
631
632
Returns:
633
str: Single eager transformation string with optional format
634
"""
635
636
def build_custom_headers(headers):
637
"""Build custom headers string for upload.
638
639
Args:
640
headers (dict|list|str): Headers specification
641
642
Returns:
643
str: Newline-separated headers string
644
"""
645
646
def build_multi_and_sprite_params(**options):
647
"""Build parameters for multi/sprite generation methods.
648
649
Args:
650
tag (str, optional): Tag to filter assets (mutually exclusive with urls)
651
urls (list, optional): List of URLs (mutually exclusive with tag)
652
mode (str, optional): Generation mode
653
async (bool, optional): Asynchronous processing
654
notification_url (str, optional): Webhook URL for completion
655
format (str, optional): Target format
656
**options: Additional transformation options
657
658
Returns:
659
dict: Parameters for multi/sprite operations
660
661
Raises:
662
ValueError: If both 'tag' and 'urls' are provided or neither is provided
663
"""
664
665
def cleanup_params(params):
666
"""Clean and normalize parameters for signature calculation.
667
668
Args:
669
params (dict): Parameters to clean
670
671
Returns:
672
dict: Cleaned parameters with None/empty values removed
673
"""
674
675
def normalize_params(params):
676
"""Normalize Admin API parameters.
677
678
Args:
679
params (dict): Parameters to normalize
680
681
Returns:
682
dict: Normalized parameters with boolean values as strings
683
"""
684
685
def generate_transformation_string(**options):
686
"""Generate transformation string from options.
687
688
Args:
689
**options: Transformation parameters
690
691
Returns:
692
tuple: (transformation_string, remaining_options)
693
"""
694
695
def patch_fetch_format(options):
696
"""Process fetch format options for fetch type uploads.
697
698
Args:
699
options (dict): Options to modify (modified in place)
700
701
Note:
702
This function modifies the options dictionary directly
703
"""
704
705
def encode_double_array(array):
706
"""Encode nested array to pipe and comma separated string.
707
708
Args:
709
array (list): Array to encode (may contain nested arrays)
710
711
Returns:
712
str: Encoded string with format "item1,item2|item3,item4"
713
"""
714
715
def normalize_context_value(value):
716
"""Normalize context value by escaping delimiters.
717
718
Args:
719
value: Value to normalize (int, str, list, or tuple)
720
721
Returns:
722
str: Normalized value with escaped = and | characters
723
"""
724
725
def encode_date_to_usage_api_format(date_obj):
726
"""Encode date object to usage API format.
727
728
Args:
729
date_obj (datetime.date): Date object to encode
730
731
Returns:
732
str: Date string in 'dd-mm-yyyy' format
733
"""
734
735
def process_radius(param):
736
"""Process radius parameter for rounded corners.
737
738
Args:
739
param (str|int|list|tuple): Radius specification
740
741
Returns:
742
str: Processed radius parameter
743
744
Raises:
745
ValueError: If radius param has invalid length (must be 1-4 values)
746
"""
747
748
def process_params(params):
749
"""Process parameters for API submission.
750
751
Args:
752
params (dict): Parameters to process
753
754
Returns:
755
dict: Processed parameters with array handling
756
"""
757
758
def breakpoint_settings_mapper(breakpoint_settings):
759
"""Map responsive breakpoint settings.
760
761
Args:
762
breakpoint_settings (dict): Breakpoint configuration
763
764
Returns:
765
dict: Mapped breakpoint settings with transformation string
766
"""
767
768
def generate_responsive_breakpoints_string(breakpoints):
769
"""Generate responsive breakpoints JSON string.
770
771
Args:
772
breakpoints (list): List of breakpoint configurations
773
774
Returns:
775
str: JSON string representation of breakpoints
776
"""
777
778
def finalize_source(source, format, url_suffix):
779
"""Finalize resource source with format and URL suffix.
780
781
Args:
782
source (str): Resource source identifier
783
format (str): Resource format
784
url_suffix (str): URL suffix to append
785
786
Returns:
787
tuple: (finalized_source, source_to_sign)
788
"""
789
790
def finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten):
791
"""Finalize resource type and upload type for URL generation.
792
793
Args:
794
resource_type (str): Resource type ('image', 'video', 'raw')
795
type (str): Upload type ('upload', 'private', etc.)
796
url_suffix (str): URL suffix
797
use_root_path (bool): Whether to use root path
798
shorten (bool): Whether to use shortened URLs
799
800
Returns:
801
tuple: (finalized_resource_type, finalized_type)
802
"""
803
804
def check_property_enabled(f):
805
"""Decorator to check if class property is enabled.
806
807
Args:
808
f (function): Function to wrap
809
810
Returns:
811
function: Wrapped function that checks self.enabled
812
"""
813
814
def get_http_connector(conf, options):
815
"""Create HTTP connector based on configuration.
816
817
Args:
818
conf: Configuration object
819
options (dict): Additional connector options
820
821
Returns:
822
HTTP connector (PoolManager or ProxyManager)
823
"""
824
825
def process_custom_function(custom_function):
826
"""Process custom function parameter for transformations.
827
828
Args:
829
custom_function (str|dict): Custom function specification
830
831
Returns:
832
str: Processed custom function parameter
833
"""
834
835
def process_custom_pre_function(custom_function):
836
"""Process custom pre-function parameter for transformations.
837
838
Args:
839
custom_function (str|dict): Custom pre-function specification
840
841
Returns:
842
str: Processed custom pre-function parameter with 'pre:' prefix
843
"""
844
845
def process_conditional(conditional):
846
"""Process conditional transformation parameter.
847
848
Args:
849
conditional: Conditional expression
850
851
Returns:
852
str: Normalized conditional expression
853
"""
854
855
def encode_unicode_url(url_str):
856
"""Encode unicode URL string for safe transmission.
857
858
Args:
859
url_str (str): URL string to encode
860
861
Returns:
862
str: Encoded URL string
863
"""
864
865
def split_range(range):
866
"""Split range specification into start and end values.
867
868
Args:
869
range (str|list|tuple): Range specification (e.g., "10..20" or [10, 20])
870
871
Returns:
872
list|None: [start, end] values or None if invalid format
873
"""
874
875
def norm_range_value(value):
876
"""Normalize range value with percentage modifier.
877
878
Args:
879
value: Range value to normalize
880
881
Returns:
882
str|None: Normalized range value with 'p' modifier for percentages
883
"""
884
885
def norm_auto_range_value(value):
886
"""Normalize auto range value, preserving 'auto' keyword.
887
888
Args:
889
value: Range value to normalize (may be 'auto')
890
891
Returns:
892
str|None: Normalized range value or 'auto'
893
"""
894
895
def is_fraction(width):
896
"""Check if width value represents a fraction less than 1.
897
898
Args:
899
width: Width value to check
900
901
Returns:
902
bool: True if width is a decimal fraction less than 1
903
"""
904
905
def unsigned_download_url_prefix(source, cloud_name, private_cdn, cdn_subdomain,
906
secure_cdn_subdomain, cname, secure, secure_distribution):
907
"""Generate URL prefix for unsigned downloads.
908
909
Args:
910
source (str): Resource source identifier
911
cloud_name (str): Cloudinary cloud name
912
private_cdn (bool): Whether using private CDN
913
cdn_subdomain (bool): Whether to use CDN subdomains
914
secure_cdn_subdomain (bool): Whether to use secure CDN subdomains
915
cname (str): Custom domain name
916
secure (bool): Whether to use HTTPS
917
secure_distribution (str): Secure distribution domain
918
919
Returns:
920
str: URL prefix for resource downloads
921
"""
922
```
923
924
## Usage Examples
925
926
### Basic URL Generation
927
928
```python
929
from cloudinary.utils import cloudinary_url
930
931
# Simple image URL
932
url, options = cloudinary_url("sample")
933
print(url) # https://res.cloudinary.com/demo/image/upload/sample
934
935
# URL with basic transformations
936
url, options = cloudinary_url(
937
"sample",
938
width=300,
939
height=200,
940
crop="fill"
941
)
942
943
# HTTPS URL with format optimization
944
url, options = cloudinary_url(
945
"sample",
946
secure=True,
947
quality="auto",
948
format="auto"
949
)
950
```
951
952
### Advanced Image Transformations
953
954
```python
955
# Complex image transformation chain
956
url, options = cloudinary_url(
957
"sample",
958
transformation=[
959
{"width": 1000, "height": 1000, "crop": "limit"},
960
{"quality": "auto", "format": "auto"},
961
{"effect": "sharpen", "radius": 3},
962
{"border": "5px_solid_black"}
963
]
964
)
965
966
# Responsive image with automatic DPR
967
url, options = cloudinary_url(
968
"sample",
969
width=400,
970
height=300,
971
crop="fill",
972
dpr="auto",
973
responsive_breakpoints=[
974
{"max_width": 1000, "max_images": 5},
975
{"max_width": 500, "max_images": 3}
976
]
977
)
978
979
# Image with overlay and effects
980
url, options = cloudinary_url(
981
"sample",
982
width=500,
983
height=500,
984
crop="fill",
985
overlay="text:Arial_60:Hello%20World",
986
gravity="south",
987
y=20,
988
color="white",
989
effect="shadow"
990
)
991
```
992
993
### Video Transformations
994
995
```python
996
# Video resizing and format conversion
997
url, options = cloudinary_url(
998
"sample_video",
999
resource_type="video",
1000
width=640,
1001
height=480,
1002
crop="pad",
1003
format="mp4",
1004
video_codec="h264",
1005
audio_codec="aac"
1006
)
1007
1008
# Video with effects and trimming
1009
url, options = cloudinary_url(
1010
"sample_video",
1011
resource_type="video",
1012
width=800,
1013
height=600,
1014
crop="fill",
1015
start_offset="10s",
1016
duration="30s",
1017
effect="sepia",
1018
quality="auto"
1019
)
1020
1021
# Generate video thumbnail
1022
url, options = cloudinary_url(
1023
"sample_video",
1024
resource_type="video",
1025
format="jpg",
1026
start_offset="50%",
1027
width=400,
1028
height=300,
1029
crop="fill"
1030
)
1031
```
1032
1033
### HTML Tag Generation
1034
1035
```python
1036
from cloudinary.utils import cloudinary_tag
1037
1038
# Basic image tag
1039
tag = cloudinary_tag(
1040
"sample",
1041
width=300,
1042
height=200,
1043
crop="fill",
1044
alt="Sample image"
1045
)
1046
print(tag) # <img src="..." width="300" height="200" alt="Sample image">
1047
1048
# Responsive image tag
1049
tag = cloudinary_tag(
1050
"sample",
1051
width=400,
1052
height=300,
1053
crop="fill",
1054
responsive=True,
1055
client_hints=True,
1056
class="responsive-image",
1057
alt="Responsive sample"
1058
)
1059
1060
# Image with lazy loading
1061
tag = cloudinary_tag(
1062
"sample",
1063
width=300,
1064
height=200,
1065
crop="fill",
1066
loading="lazy",
1067
class="lazy-image"
1068
)
1069
```
1070
1071
### Archive Creation
1072
1073
```python
1074
from cloudinary.utils import create_archive_url, create_zip_url
1075
1076
# Create ZIP from specific images
1077
zip_url = create_zip_url(
1078
public_ids=["image1", "image2", "image3"],
1079
target_format="zip"
1080
)
1081
1082
# Create archive from tagged images
1083
archive_url = create_archive_url(
1084
tags=["product"],
1085
target_format="tgz",
1086
resource_type="image",
1087
flatten_folders=True
1088
)
1089
1090
# Create archive with transformations
1091
archive_url = create_archive_url(
1092
prefixes=["products/"],
1093
transformations=[
1094
{"width": 800, "height": 600, "crop": "fit"}
1095
],
1096
target_format="zip"
1097
)
1098
```
1099
1100
### Advanced Features
1101
1102
```python
1103
# Signed URL for private resources
1104
url, options = cloudinary_url(
1105
"private_image",
1106
type="private",
1107
sign_url=True,
1108
width=400,
1109
height=300
1110
)
1111
1112
# Auto-optimization with Client Hints
1113
url, options = cloudinary_url(
1114
"sample",
1115
width=400,
1116
height=300,
1117
crop="fill",
1118
dpr="auto",
1119
quality="auto",
1120
format="auto",
1121
fetch_format="auto"
1122
)
1123
1124
# Progressive JPEG with quality analysis
1125
url, options = cloudinary_url(
1126
"sample",
1127
width=800,
1128
height=600,
1129
quality="auto:good",
1130
flags="progressive",
1131
format="jpg"
1132
)
1133
1134
# Image with face detection crop
1135
url, options = cloudinary_url(
1136
"portrait",
1137
width=300,
1138
height=300,
1139
crop="thumb",
1140
gravity="face"
1141
)
1142
1143
# Conditional transformations
1144
url, options = cloudinary_url(
1145
"sample",
1146
transformation=[
1147
{"if": "w_gt_300", "width": 300, "height": 300, "crop": "scale"},
1148
{"if": "else", "width": 150, "height": 150, "crop": "scale"}
1149
]
1150
)
1151
```
1152
1153
### Resource-Specific URLs
1154
1155
```python
1156
# Fetch external image and transform
1157
url, options = cloudinary_url(
1158
"https://example.com/image.jpg",
1159
type="fetch",
1160
width=400,
1161
height=300,
1162
crop="fill",
1163
quality="auto"
1164
)
1165
1166
# Auto-upload from external URL
1167
url, options = cloudinary_url(
1168
"https://example.com/image.jpg",
1169
type="auto",
1170
width=400,
1171
height=300,
1172
crop="fill"
1173
)
1174
1175
# Private asset with authentication
1176
url, options = cloudinary_url(
1177
"private_asset",
1178
type="authenticated",
1179
auth_token={
1180
"key": "your_auth_key",
1181
"duration": 3600,
1182
"start_time": 1234567890
1183
}
1184
)
1185
```
1186
1187
### Utility Functions Usage
1188
1189
```python
1190
from cloudinary.utils import (
1191
private_download_url, generate_auth_token, smart_escape,
1192
random_public_id, signed_preloaded_image, build_array,
1193
encode_context, merge, fq_public_id, compute_hex_hash,
1194
verify_api_response_signature
1195
)
1196
1197
# Generate private download URL
1198
download_url = private_download_url(
1199
"my_private_image",
1200
"jpg",
1201
type="private",
1202
attachment=True,
1203
expires_at=1234567890
1204
)
1205
1206
# Generate authentication token
1207
auth_token = generate_auth_token(
1208
key="my_auth_key",
1209
duration=3600,
1210
acl="/image/*"
1211
)
1212
1213
# URL encode special characters
1214
escaped_path = smart_escape("path with spaces/special chars!")
1215
1216
# Generate random public ID
1217
random_id = random_public_id()
1218
print(random_id) # e.g., "a3f2k8n9m1p4q7s2"
1219
1220
# Create signed preloaded image path
1221
upload_result = {
1222
"public_id": "sample",
1223
"version": "1234567890",
1224
"format": "jpg",
1225
"signature": "abc123def456"
1226
}
1227
signed_path = signed_preloaded_image(upload_result)
1228
print(signed_path) # "image/upload/v1234567890/sample.jpg#abc123def456"
1229
1230
# Build array from various inputs
1231
array1 = build_array("single_value") # ["single_value"]
1232
array2 = build_array(["a", "b", "c"]) # ["a", "b", "c"]
1233
array3 = build_array(None) # []
1234
1235
# Encode context metadata
1236
context = {"key1": "value1", "key2": ["list", "value"]}
1237
encoded = encode_context(context)
1238
print(encoded) # "key1=value1|key2=[\"list\",\"value\"]"
1239
1240
# Merge multiple dictionaries
1241
options = merge(
1242
{"width": 400, "height": 300},
1243
{"crop": "fill", "quality": "auto"},
1244
{"format": "webp"}
1245
)
1246
1247
# Generate fully qualified public ID
1248
fq_id = fq_public_id("sample", "video", "upload")
1249
print(fq_id) # "video/upload/sample"
1250
1251
# Compute hash for signature verification
1252
hash_value = compute_hex_hash("data_to_hash", "sha256")
1253
1254
# Verify API response signature
1255
is_valid = verify_api_response_signature(
1256
public_id="sample",
1257
version="1234567890",
1258
signature="received_signature"
1259
)
1260
```
1261
1262
### Advanced Processing Examples
1263
1264
```python
1265
from cloudinary.utils import (
1266
process_layer, chain_transformations, build_upload_params,
1267
archive_params, handle_file_parameter, json_encode,
1268
base64url_encode, unique, safe_cast
1269
)
1270
1271
# Process overlay layer with text
1272
text_overlay = process_layer({
1273
"text": "Hello World",
1274
"font_family": "Arial",
1275
"font_size": 40,
1276
"color": "white"
1277
}, "overlay")
1278
1279
# Chain transformations
1280
base_options = {"width": 400, "height": 300, "crop": "fill"}
1281
additional_transforms = [
1282
{"effect": "sharpen"},
1283
{"border": "5px_solid_black"}
1284
]
1285
chained_options = chain_transformations(base_options, additional_transforms)
1286
1287
# Build upload parameters with metadata
1288
upload_params = build_upload_params(
1289
public_id="sample_upload",
1290
tags=["product", "featured"],
1291
metadata={"category": "electronics", "price": 99.99},
1292
transformation={"width": 800, "height": 600, "crop": "fit"}
1293
)
1294
1295
# Create archive parameters
1296
archive_config = archive_params(
1297
tags=["product"],
1298
target_format="zip",
1299
flatten_folders=True,
1300
transformations=[{"width": 400, "height": 300, "crop": "fill"}]
1301
)
1302
1303
# Handle different file types for upload
1304
file_data1 = handle_file_parameter("/path/to/image.jpg")
1305
file_data2 = handle_file_parameter("https://example.com/image.jpg")
1306
file_data3 = handle_file_parameter(open("/path/to/image.jpg", "rb"))
1307
1308
# JSON encoding with custom serializer
1309
data = {"timestamp": datetime.now(), "values": [1, 2, 3]}
1310
json_string = json_encode(data)
1311
1312
# URL-safe Base64 encoding
1313
encoded_data = base64url_encode("Hello, World!")
1314
1315
# Remove duplicates while preserving order
1316
items = ["a", "b", "a", "c", "b", "d"]
1317
unique_items = unique(items)
1318
print(unique_items) # ["a", "b", "c", "d"]
1319
1320
# Safe type casting with fallback
1321
safe_int = safe_cast("123", int, 0) # 123
1322
safe_int_fail = safe_cast("abc", int, 0) # 0
1323
```
1324
1325
### Signature Verification Examples
1326
1327
```python
1328
from cloudinary.utils import (
1329
api_sign_request, verify_api_response_signature,
1330
verify_notification_signature, compute_hex_hash
1331
)
1332
1333
# Sign API request parameters
1334
params = {
1335
"public_id": "sample",
1336
"timestamp": "1234567890",
1337
"transformation": "w_400,h_300,c_fill"
1338
}
1339
signature = api_sign_request(
1340
params,
1341
api_secret="your_api_secret",
1342
algorithm="sha256",
1343
signature_version=2
1344
)
1345
1346
# Verify webhook notification
1347
webhook_body = '{"public_id":"sample","version":1234567890}'
1348
timestamp = 1234567890
1349
received_signature = "webhook_signature_from_header"
1350
1351
is_valid_notification = verify_notification_signature(
1352
body=webhook_body,
1353
timestamp=timestamp,
1354
signature=received_signature,
1355
valid_for=7200 # 2 hours
1356
)
1357
1358
if is_valid_notification:
1359
print("Webhook notification is authentic")
1360
else:
1361
print("Invalid or expired webhook notification")
1362
1363
# Manual hash computation for custom verification
1364
data_to_hash = "sensitive_data" + "secret_key"
1365
hash_result = compute_hex_hash(data_to_hash, "sha256")
1366
```