0
# Configuration and Setup
1
2
Complete configuration management for Cloudinary account credentials, default transformation parameters, and SDK behavior settings.
3
4
## Capabilities
5
6
### Global Configuration
7
8
Configure Cloudinary account settings and default parameters that apply to all operations.
9
10
```python { .api }
11
def config(**keywords):
12
"""Configure Cloudinary account settings and defaults.
13
14
Args:
15
cloud_name (str): Your Cloudinary cloud name (required)
16
api_key (str): Your API key (required for upload/admin operations)
17
api_secret (str): Your API secret (required for upload/admin operations)
18
secure (bool, optional): Use HTTPS URLs (default: True)
19
cdn_subdomain (bool, optional): Use multiple CDN subdomains for better performance
20
secure_cdn_subdomain (bool, optional): Use HTTPS CDN subdomains
21
private_cdn (bool, optional): Use private CDN distribution
22
cname (str, optional): Custom domain name for asset URLs
23
upload_prefix (str, optional): Custom upload URL prefix
24
api_proxy (str, optional): Proxy URL for API calls
25
auth_token (dict, optional): Default authentication token configuration
26
**kwargs: Additional configuration options
27
28
Returns:
29
Config: Configuration object with current settings
30
"""
31
32
def reset_config():
33
"""Reset configuration to default values.
34
35
Returns:
36
None
37
"""
38
39
def get_user_agent():
40
"""Get the current user agent string used for API requests.
41
42
Returns:
43
str: User agent string including platform information
44
"""
45
```
46
47
### Configuration Class
48
49
Main configuration object that holds all Cloudinary settings.
50
51
```python { .api }
52
class Config:
53
"""Configuration object for Cloudinary settings.
54
55
Attributes:
56
cloud_name (str): Cloudinary cloud name
57
api_key (str): API key for authenticated operations
58
api_secret (str): API secret for authenticated operations
59
secure (bool): Whether to use HTTPS URLs
60
cdn_subdomain (bool): Whether to use CDN subdomains
61
private_cdn (bool): Whether to use private CDN
62
cname (str): Custom domain name
63
auth_token (dict): Default authentication token settings
64
"""
65
66
def __init__(self, **options):
67
"""Initialize configuration with provided options."""
68
69
def __getattr__(self, key):
70
"""Get configuration value by attribute name."""
71
72
def __setattr__(self, key, value):
73
"""Set configuration value by attribute name."""
74
```
75
76
### Resource Classes
77
78
Base classes for working with Cloudinary media assets.
79
80
```python { .api }
81
class CloudinaryResource:
82
"""Base class for Cloudinary media resources.
83
84
Provides URL generation and transformation capabilities common to all resource types.
85
"""
86
87
def __init__(self, public_id=None, format=None, version=None, signature=None, **options):
88
"""Initialize a Cloudinary resource.
89
90
Args:
91
public_id (str, optional): Public identifier for the resource
92
format (str, optional): File format (jpg, png, webp, etc.)
93
version (str, optional): Version identifier
94
signature (str, optional): Signature for signed URLs
95
**options: Additional resource options
96
"""
97
98
def build_url(self, **options):
99
"""Build a URL for this resource with optional transformations.
100
101
Args:
102
**options: Transformation and URL generation options
103
104
Returns:
105
str: Generated Cloudinary URL
106
"""
107
108
def __unicode__(self):
109
"""Return string representation of the resource."""
110
111
def __str__(self):
112
"""Return string representation of the resource."""
113
114
class CloudinaryImage(CloudinaryResource):
115
"""Image-specific resource class with image transformation capabilities.
116
117
Extends CloudinaryResource with image-specific functionality and transformations.
118
"""
119
120
def image(self, **options):
121
"""Generate HTML img tag for this image.
122
123
Args:
124
**options: Image transformation and HTML attributes
125
126
Returns:
127
str: HTML img tag with Cloudinary URL
128
"""
129
130
class CloudinaryVideo(CloudinaryResource):
131
"""Video-specific resource class with video transformation capabilities.
132
133
Extends CloudinaryResource with video-specific functionality and transformations.
134
"""
135
136
def video(self, **options):
137
"""Generate HTML video tag for this video.
138
139
Args:
140
**options: Video transformation and HTML attributes
141
142
Returns:
143
str: HTML video tag with Cloudinary URL
144
"""
145
```
146
147
## Usage Examples
148
149
### Basic Configuration
150
151
```python
152
import cloudinary
153
154
# Configure with account credentials
155
cloudinary.config(
156
cloud_name="demo",
157
api_key="123456789012345",
158
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx"
159
)
160
161
# Configure with additional options
162
cloudinary.config(
163
cloud_name="demo",
164
api_key="123456789012345",
165
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx",
166
secure=True,
167
cdn_subdomain=True,
168
private_cdn=False,
169
auth_token={
170
"key": "your_auth_key",
171
"duration": 3600
172
}
173
)
174
```
175
176
### Environment Variables
177
178
```python
179
import os
180
import cloudinary
181
182
# Set environment variables
183
os.environ['CLOUDINARY_URL'] = 'cloudinary://api_key:api_secret@cloud_name'
184
185
# Or configure individual components
186
os.environ['CLOUDINARY_CLOUD_NAME'] = 'demo'
187
os.environ['CLOUDINARY_API_KEY'] = '123456789012345'
188
os.environ['CLOUDINARY_API_SECRET'] = 'abcd_efgh_ijkl_mnop_qrst_uvwx'
189
190
# Import Django settings (if using Django)
191
cloudinary.import_django_settings()
192
```
193
194
### Resource Creation and URL Generation
195
196
```python
197
from cloudinary import CloudinaryImage, CloudinaryVideo
198
199
# Create image resource
200
image = CloudinaryImage("sample")
201
image_url = image.build_url(width=300, height=200, crop="fill")
202
203
# Create image with version and format
204
versioned_image = CloudinaryImage("sample", version=1234567890, format="jpg")
205
versioned_url = versioned_image.build_url(quality="auto")
206
207
# Create video resource
208
video = CloudinaryVideo("sample_video")
209
video_url = video.build_url(width=640, height=480, crop="pad")
210
211
# Generate HTML tags
212
img_tag = CloudinaryImage("sample").image(width=300, height=200, alt="Sample image")
213
video_tag = CloudinaryVideo("sample_video").video(width=640, height=480, controls=True)
214
```
215
216
### Authentication Tokens
217
218
Generate and manage authentication tokens for secure URL access and API operations.
219
220
```python { .api }
221
def generate(url=None, acl=None, start_time=None, duration=None,
222
expiration=None, ip=None, key=None, token_name="__cld_token__", **kwargs):
223
"""Generate an authentication token for secure Cloudinary URLs.
224
225
Args:
226
url (str, optional): Specific URL to authenticate (mutually exclusive with acl)
227
acl (str or list, optional): Access control list - URLs patterns to authenticate
228
start_time (int, optional): Token validity start time (Unix timestamp)
229
duration (int, optional): Token validity duration in seconds
230
expiration (int, optional): Token expiration time (Unix timestamp)
231
ip (str, optional): IP address restriction for token usage
232
key (str, optional): Secret key for HMAC signature generation
233
token_name (str, optional): Name for the token parameter (default: "__cld_token__")
234
**kwargs: Additional token parameters
235
236
Returns:
237
str: Generated authentication token string in format "token_name=token_value"
238
239
Raises:
240
Exception: If neither expiration nor duration is provided
241
Exception: If neither acl nor url is provided
242
"""
243
244
def generate_auth_token(**options):
245
"""Generate authentication token using configuration defaults.
246
247
Args:
248
**options: Token generation options (same as generate function)
249
250
Returns:
251
str: Generated authentication token string
252
"""
253
254
# Constants
255
AUTH_TOKEN_NAME = "__cld_token__"
256
AUTH_TOKEN_SEPARATOR = "~"
257
```
258
259
### Configuration Management
260
261
```python
262
import cloudinary
263
264
# Get current configuration
265
current_config = cloudinary.config()
266
print(f"Cloud name: {current_config.cloud_name}")
267
268
# Update specific settings
269
cloudinary.config(secure=True, cdn_subdomain=True)
270
271
# Reset to defaults
272
cloudinary.reset_config()
273
274
# Check user agent
275
user_agent = cloudinary.get_user_agent()
276
print(f"User agent: {user_agent}")
277
```
278
279
### Authentication Token Examples
280
281
```python
282
from cloudinary import auth_token
283
import cloudinary
284
285
# Basic token generation with duration
286
token = auth_token.generate(
287
key="your_secret_key",
288
duration=3600, # 1 hour validity
289
acl="/image/upload/*" # Allow uploads to image/upload path
290
)
291
print(token) # "__cld_token__=ip=...~st=...~exp=...~acl=...~hmac=..."
292
293
# Token with specific URL and IP restriction
294
token = auth_token.generate(
295
key="your_secret_key",
296
url="/image/upload/sample.jpg",
297
ip="192.168.1.100",
298
expiration=1640995200 # Specific expiration timestamp
299
)
300
301
# Token for multiple ACL patterns
302
token = auth_token.generate(
303
key="your_secret_key",
304
duration=7200, # 2 hours
305
acl=["/image/*", "/video/*"], # Allow access to image and video paths
306
start_time=1640908800 # Custom start time
307
)
308
309
# Using configuration defaults
310
cloudinary.config(
311
cloud_name="demo",
312
api_key="123456789012345",
313
api_secret="abcd_efgh_ijkl_mnop_qrst_uvwx",
314
auth_token={
315
"key": "your_secret_key",
316
"duration": 3600
317
}
318
)
319
320
# Generate token using config defaults
321
from cloudinary.utils import generate_auth_token
322
token = generate_auth_token(acl="/image/private/*")
323
324
# Use token in URL generation
325
from cloudinary.utils import cloudinary_url
326
url, options = cloudinary_url(
327
"private_image",
328
type="authenticated",
329
auth_token={
330
"key": "your_secret_key",
331
"duration": 3600,
332
"acl": "/image/authenticated/*"
333
}
334
)
335
```