or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdcdn-management.mdcloud-computing.mdcommunication-services.mdconfiguration-utilities.mddata-processing.mdfile-storage.mdindex.md

cdn-management.mddocs/

0

# CDN Management

1

2

Content delivery network cache management, domain configuration, and traffic statistics for optimizing content delivery performance and managing CDN-related operations.

3

4

## Capabilities

5

6

### CDN Cache Management

7

8

Cache refresh, prefetch operations, and traffic statistics through the `CdnManager` class.

9

10

```python { .api }

11

class CdnManager:

12

def __init__(self, auth: Auth):

13

"""

14

Initialize CDN manager.

15

16

Args:

17

auth: Auth instance for authentication

18

"""

19

20

def refresh_urls(self, urls: list) -> tuple:

21

"""

22

Refresh cache for specific URLs.

23

24

Args:

25

urls: List of URLs to refresh

26

27

Returns:

28

(dict, ResponseInfo): Refresh result and response info

29

"""

30

31

def refresh_dirs(self, dirs: list) -> tuple:

32

"""

33

Refresh cache for directories.

34

35

Args:

36

dirs: List of directory URLs to refresh

37

38

Returns:

39

(dict, ResponseInfo): Refresh result and response info

40

"""

41

42

def refresh_urls_and_dirs(self, urls: list, dirs: list) -> tuple:

43

"""

44

Refresh cache for both URLs and directories.

45

46

Args:

47

urls: List of URLs to refresh

48

dirs: List of directory URLs to refresh

49

50

Returns:

51

(dict, ResponseInfo): Refresh result and response info

52

"""

53

54

def prefetch_urls(self, urls: list) -> tuple:

55

"""

56

Prefetch files to CDN edge nodes.

57

58

Args:

59

urls: List of URLs to prefetch

60

61

Returns:

62

(dict, ResponseInfo): Prefetch result and response info

63

"""

64

65

def get_bandwidth_data(self, domains: list, start_date: str, end_date: str, granularity: str, data_type: str = None) -> tuple:

66

"""

67

Get bandwidth statistics.

68

69

Args:

70

domains: List of domain names

71

start_date: Start date (YYYY-MM-DD format)

72

end_date: End date (YYYY-MM-DD format)

73

granularity: Data granularity ('5min', 'hour', 'day')

74

data_type: Data type from DataType enum (optional)

75

76

Returns:

77

(dict, ResponseInfo): Bandwidth data and response info

78

"""

79

80

def get_flux_data(self, domains: list, start_date: str, end_date: str, granularity: str, data_type: str = None) -> tuple:

81

"""

82

Get traffic statistics.

83

84

Args:

85

domains: List of domain names

86

start_date: Start date (YYYY-MM-DD format)

87

end_date: End date (YYYY-MM-DD format)

88

granularity: Data granularity ('5min', 'hour', 'day')

89

data_type: Data type from DataType enum (optional)

90

91

Returns:

92

(dict, ResponseInfo): Traffic data and response info

93

"""

94

95

def get_log_list_data(self, domains: list, log_date: str) -> tuple:

96

"""

97

Get CDN log download links.

98

99

Args:

100

domains: List of domain names

101

log_date: Log date (YYYY-MM-DD format)

102

103

Returns:

104

(dict, ResponseInfo): Log download links and response info

105

"""

106

107

def put_httpsconf(self, name: str, certid: str, forceHttps: bool = False) -> tuple:

108

"""

109

Update HTTPS certificate configuration.

110

111

Args:

112

name: Domain name

113

certid: Certificate ID

114

forceHttps: Force HTTPS redirect

115

116

Returns:

117

(dict, ResponseInfo): Configuration result and response info

118

"""

119

```

120

121

### Domain Management

122

123

Advanced domain configuration and SSL certificate management through the `DomainManager` class.

124

125

```python { .api }

126

class DomainManager:

127

def __init__(self, auth: Auth):

128

"""

129

Initialize domain manager.

130

131

Args:

132

auth: Auth instance for authentication

133

"""

134

135

def create_domain(self, name: str, body: dict) -> tuple:

136

"""

137

Create new domain configuration.

138

139

Args:

140

name: Domain name

141

body: Domain configuration dictionary

142

143

Returns:

144

(dict, ResponseInfo): Creation result and response info

145

"""

146

147

def domain_online(self, name: str) -> tuple:

148

"""

149

Bring domain online.

150

151

Args:

152

name: Domain name

153

154

Returns:

155

(dict, ResponseInfo): Operation result and response info

156

"""

157

158

def domain_offline(self, name: str) -> tuple:

159

"""

160

Take domain offline.

161

162

Args:

163

name: Domain name

164

165

Returns:

166

(dict, ResponseInfo): Operation result and response info

167

"""

168

169

def delete_domain(self, name: str) -> tuple:

170

"""

171

Delete domain configuration.

172

173

Args:

174

name: Domain name

175

176

Returns:

177

(dict, ResponseInfo): Deletion result and response info

178

"""

179

180

def get_domain(self, name: str) -> tuple:

181

"""

182

Get domain configuration information.

183

184

Args:

185

name: Domain name

186

187

Returns:

188

(dict, ResponseInfo): Domain info and response info

189

"""

190

191

def put_httpsconf(self, name: str, certid: str, forceHttps: bool) -> tuple:

192

"""

193

Update HTTPS configuration.

194

195

Args:

196

name: Domain name

197

certid: Certificate ID

198

forceHttps: Force HTTPS redirect

199

200

Returns:

201

(dict, ResponseInfo): Configuration result and response info

202

"""

203

204

def create_sslcert(self, name: str, common_name: str, pri: str, ca: str) -> tuple:

205

"""

206

Create SSL certificate.

207

208

Args:

209

name: Certificate name

210

common_name: Certificate common name

211

pri: Private key content

212

ca: Certificate authority content

213

214

Returns:

215

(dict, ResponseInfo): Certificate creation result and response info

216

"""

217

```

218

219

### CDN Data Types

220

221

Constants for specifying data types in statistics queries.

222

223

```python { .api }

224

class DataType:

225

"""CDN data type constants for statistics queries."""

226

BANDWIDTH = 'bandwidth'

227

X302BANDWIDTH = '302bandwidth'

228

X302MBANDWIDTH = '302mbandwidth'

229

FLOW = 'flow'

230

X302FLOW = '302flow'

231

X302MFLOW = '302mflow'

232

```

233

234

### Anti-Leech URL Generation

235

236

Utility function for creating secure URLs with timestamp-based access control.

237

238

```python { .api }

239

def create_timestamp_anti_leech_url(host: str, file_name: str, query_string: str, encrypt_key: str, deadline: int) -> str:

240

"""

241

Create timestamp-based anti-leech URL.

242

243

Args:

244

host: Domain host

245

file_name: File path

246

query_string: URL query string

247

encrypt_key: Encryption key for signature

248

deadline: URL expiration timestamp

249

250

Returns:

251

Secure URL with anti-leech protection

252

"""

253

```

254

255

## Usage Examples

256

257

### Cache Management

258

259

```python

260

from qiniu import Auth, CdnManager

261

262

auth = Auth(access_key, secret_key)

263

cdn_manager = CdnManager(auth)

264

265

# Refresh specific URLs

266

urls_to_refresh = [

267

'https://cdn.example.com/image1.jpg',

268

'https://cdn.example.com/image2.png'

269

]

270

ret, info = cdn_manager.refresh_urls(urls_to_refresh)

271

272

if info.ok():

273

print(f"Refresh request ID: {ret['requestId']}")

274

else:

275

print(f"Refresh failed: {info.error}")

276

277

# Refresh directories

278

dirs_to_refresh = [

279

'https://cdn.example.com/images/',

280

'https://cdn.example.com/videos/'

281

]

282

ret, info = cdn_manager.refresh_dirs(dirs_to_refresh)

283

284

# Prefetch popular content

285

popular_urls = [

286

'https://cdn.example.com/popular-video.mp4',

287

'https://cdn.example.com/trending-image.jpg'

288

]

289

ret, info = cdn_manager.prefetch_urls(popular_urls)

290

```

291

292

### Traffic Statistics

293

294

```python

295

from qiniu import Auth, CdnManager, DataType

296

297

auth = Auth(access_key, secret_key)

298

cdn_manager = CdnManager(auth)

299

300

# Get bandwidth data for last 7 days

301

domains = ['cdn.example.com', 'static.example.com']

302

ret, info = cdn_manager.get_bandwidth_data(

303

domains=domains,

304

start_date='2024-01-01',

305

end_date='2024-01-07',

306

granularity='day',

307

data_type=DataType.BANDWIDTH

308

)

309

310

if info.ok():

311

for time_point in ret['data']:

312

timestamp = time_point['time']

313

bandwidth = time_point['values']['bandwidth']

314

print(f"Time: {timestamp}, Bandwidth: {bandwidth} bps")

315

316

# Get traffic data

317

ret, info = cdn_manager.get_flux_data(

318

domains=domains,

319

start_date='2024-01-01',

320

end_date='2024-01-07',

321

granularity='hour',

322

data_type=DataType.FLOW

323

)

324

325

if info.ok():

326

total_traffic = sum(point['values']['flow'] for point in ret['data'])

327

print(f"Total traffic: {total_traffic} bytes")

328

```

329

330

### Domain Management

331

332

```python

333

from qiniu import Auth, DomainManager

334

335

auth = Auth(access_key, secret_key)

336

domain_manager = DomainManager(auth)

337

338

# Create new domain

339

domain_config = {

340

'name': 'cdn.example.com',

341

'type': 'normal',

342

'sources': [

343

{

344

'source': 'origin.example.com',

345

'host': 'origin.example.com'

346

}

347

]

348

}

349

350

ret, info = domain_manager.create_domain('cdn.example.com', domain_config)

351

352

if info.ok():

353

print("Domain created successfully")

354

355

# Get domain information

356

ret, info = domain_manager.get_domain('cdn.example.com')

357

if info.ok():

358

print(f"Domain status: {ret['operatingState']}")

359

print(f"CNAME: {ret['cname']}")

360

361

# Configure HTTPS

362

ret, info = domain_manager.put_httpsconf(

363

name='cdn.example.com',

364

certid='cert-id-123',

365

forceHttps=True

366

)

367

368

# Take domain offline for maintenance

369

ret, info = domain_manager.domain_offline('cdn.example.com')

370

print(f"Domain offline result: {info.ok()}")

371

372

# Bring domain back online

373

ret, info = domain_manager.domain_online('cdn.example.com')

374

print(f"Domain online result: {info.ok()}")

375

```

376

377

### SSL Certificate Management

378

379

```python

380

from qiniu import Auth, DomainManager

381

382

auth = Auth(access_key, secret_key)

383

domain_manager = DomainManager(auth)

384

385

# Create SSL certificate

386

with open('private.key', 'r') as f:

387

private_key = f.read()

388

389

with open('certificate.crt', 'r') as f:

390

certificate = f.read()

391

392

ret, info = domain_manager.create_sslcert(

393

name='my-ssl-cert',

394

common_name='cdn.example.com',

395

pri=private_key,

396

ca=certificate

397

)

398

399

if info.ok():

400

cert_id = ret['certid']

401

print(f"SSL certificate created: {cert_id}")

402

403

# Apply certificate to domain

404

ret, info = domain_manager.put_httpsconf(

405

name='cdn.example.com',

406

certid=cert_id,

407

forceHttps=True

408

)

409

```

410

411

### Access Log Analysis

412

413

```python

414

from qiniu import Auth, CdnManager

415

import requests

416

417

auth = Auth(access_key, secret_key)

418

cdn_manager = CdnManager(auth)

419

420

# Get log download links

421

ret, info = cdn_manager.get_log_list_data(

422

domains=['cdn.example.com'],

423

log_date='2024-01-15'

424

)

425

426

if info.ok():

427

for domain_logs in ret['data']:

428

domain = domain_logs['domain']

429

for log_info in domain_logs['logs']:

430

log_url = log_info['url']

431

log_size = log_info['size']

432

433

print(f"Domain: {domain}")

434

print(f"Log URL: {log_url}")

435

print(f"Log size: {log_size} bytes")

436

437

# Download and process log file

438

response = requests.get(log_url)

439

if response.status_code == 200:

440

# Process log content

441

log_content = response.text

442

lines = log_content.split('\n')

443

print(f"Log entries: {len(lines)}")

444

```

445

446

### Anti-Leech Protection

447

448

```python

449

from qiniu import create_timestamp_anti_leech_url

450

import time

451

452

# Create secure URL with expiration

453

host = 'cdn.example.com'

454

file_name = '/protected/video.mp4'

455

query_string = ''

456

encrypt_key = 'your-encrypt-key'

457

deadline = int(time.time()) + 3600 # Valid for 1 hour

458

459

secure_url = create_timestamp_anti_leech_url(

460

host=host,

461

file_name=file_name,

462

query_string=query_string,

463

encrypt_key=encrypt_key,

464

deadline=deadline

465

)

466

467

print(f"Secure URL: https://{host}{secure_url}")

468

```