or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdblob-client.mdblob-types-tiers.mdcontainer-client.mdindex.mdsas-generation.mdservice-client.mdutility-functions.md

service-client.mddocs/

0

# Service Client Operations

1

2

Account-level operations for Azure Blob Storage including authentication, service configuration, container management, and cross-container operations. The BlobServiceClient serves as the main entry point for interacting with an Azure Storage account.

3

4

## Capabilities

5

6

### Client Creation and Authentication

7

8

Create BlobServiceClient instances with various authentication methods including connection strings, account keys, SAS tokens, and Azure Active Directory credentials.

9

10

```python { .api }

11

class BlobServiceClient:

12

def __init__(self, account_url: str, credential=None, **kwargs):

13

"""

14

Create a BlobServiceClient.

15

16

Args:

17

account_url (str): The URL to the blob storage account

18

credential: The credentials for authentication. Can be:

19

- str: Account key or SAS token string

20

- dict: Account name and key mapping

21

- AzureNamedKeyCredential: Named key credential

22

- AzureSasCredential: SAS credential

23

- TokenCredential: Azure AD token credential

24

- None: For anonymous access or SAS URLs

25

"""

26

27

@classmethod

28

def from_connection_string(cls, conn_str: str, credential=None, **kwargs) -> 'BlobServiceClient':

29

"""

30

Create a BlobServiceClient from a connection string.

31

32

Args:

33

conn_str (str): Azure Storage connection string

34

credential: Optional credential to override connection string auth

35

36

Returns:

37

BlobServiceClient: Configured client instance

38

"""

39

```

40

41

### Service Configuration

42

43

Retrieve and configure account-level service properties including analytics logging, metrics, CORS rules, and static website hosting.

44

45

```python { .api }

46

def get_account_information(self, **kwargs) -> dict:

47

"""

48

Get information about the storage account.

49

50

Returns:

51

dict: Account information including account kind, SKU name, and capabilities

52

"""

53

54

def get_service_properties(self, **kwargs) -> dict:

55

"""

56

Get service properties for the storage account.

57

58

Returns:

59

dict: Service properties including logging, metrics, CORS, and retention policies

60

"""

61

62

def set_service_properties(self, analytics_logging=None, hour_metrics=None, minute_metrics=None, cors=None, target_version=None, delete_retention_policy=None, static_website=None, **kwargs) -> None:

63

"""

64

Set service properties for the storage account.

65

66

Args:

67

analytics_logging (BlobAnalyticsLogging, optional): Logging configuration

68

hour_metrics (Metrics, optional): Hour metrics configuration

69

minute_metrics (Metrics, optional): Minute metrics configuration

70

cors (list[CorsRule], optional): CORS rules

71

target_version (str, optional): Target service version

72

delete_retention_policy (RetentionPolicy, optional): Soft delete configuration

73

static_website (StaticWebsite, optional): Static website configuration

74

"""

75

76

def get_service_stats(self, **kwargs) -> dict:

77

"""

78

Get statistics for the storage account (geo-replication status).

79

80

Returns:

81

dict: Service statistics including geo-replication details

82

"""

83

```

84

85

### User Delegation Keys

86

87

Obtain user delegation keys for creating user delegation SAS tokens with Azure Active Directory credentials.

88

89

```python { .api }

90

def get_user_delegation_key(self, key_start_time, key_expiry_time, **kwargs) -> 'UserDelegationKey':

91

"""

92

Get a user delegation key for creating SAS tokens.

93

94

Args:

95

key_start_time (datetime): Start time for key validity

96

key_expiry_time (datetime): Expiry time for key validity

97

98

Returns:

99

UserDelegationKey: User delegation key for SAS generation

100

"""

101

```

102

103

### Container Management

104

105

Create, delete, and list containers at the account level. These operations provide account-wide container management capabilities.

106

107

```python { .api }

108

def list_containers(self, name_starts_with=None, include_metadata=False, **kwargs) -> ItemPaged[ContainerProperties]:

109

"""

110

List containers in the storage account.

111

112

Args:

113

name_starts_with (str, optional): Filter containers by name prefix

114

include_metadata (bool): Whether to include container metadata

115

116

Returns:

117

ItemPaged[ContainerProperties]: Paginated list of container properties

118

"""

119

120

def create_container(self, name: str, metadata=None, public_access=None, **kwargs) -> ContainerClient:

121

"""

122

Create a new container.

123

124

Args:

125

name (str): Container name

126

metadata (dict, optional): Container metadata

127

public_access (PublicAccess, optional): Public access level

128

129

Returns:

130

ContainerClient: Client for the created container

131

"""

132

133

def delete_container(self, container: str, **kwargs) -> None:

134

"""

135

Delete a container.

136

137

Args:

138

container (str): Container name to delete

139

"""

140

141

def undelete_container(self, deleted_container_name: str, deleted_container_version: str, **kwargs) -> ContainerClient:

142

"""

143

Restore a soft-deleted container.

144

145

Args:

146

deleted_container_name (str): Name of deleted container

147

deleted_container_version (str): Version of deleted container

148

149

Returns:

150

ContainerClient: Client for the restored container

151

"""

152

```

153

154

### Cross-Container Blob Queries

155

156

Search for blobs across all containers in the account using blob index tags.

157

158

```python { .api }

159

def find_blobs_by_tags(self, filter_expression: str, **kwargs) -> ItemPaged['FilteredBlob']:

160

"""

161

Find blobs across the account using tag-based filtering.

162

163

Args:

164

filter_expression (str): OData filter expression for blob tags

165

166

Returns:

167

ItemPaged[FilteredBlob]: Paginated list of matching blobs

168

"""

169

```

170

171

### Client Factory Methods

172

173

Create container and blob clients from the service client for hierarchical access to storage resources.

174

175

```python { .api }

176

def get_container_client(self, container: str) -> 'ContainerClient':

177

"""

178

Get a ContainerClient for a specific container.

179

180

Args:

181

container (str): Container name

182

183

Returns:

184

ContainerClient: Client for container operations

185

"""

186

187

def get_blob_client(self, container: Union[ContainerProperties, str], blob: str, snapshot: Optional[Union[Dict[str, Any], str]] = None, *, version_id: Optional[str] = None) -> BlobClient:

188

"""

189

Get a BlobClient for a specific blob.

190

191

Args:

192

container (Union[ContainerProperties, str]): Container name or container properties object

193

blob (str): Blob name

194

snapshot (Optional[Union[Dict[str, Any], str]]): Blob snapshot identifier or snapshot properties dict

195

version_id (Optional[str]): Version ID to target a specific version of the blob

196

197

Returns:

198

BlobClient: Client for blob operations

199

"""

200

```

201

202

## Configuration Options

203

204

The BlobServiceClient accepts various configuration options in the constructor:

205

206

```python { .api }

207

# Common configuration options

208

BlobServiceClient(

209

account_url="https://account.blob.core.windows.net",

210

credential=credential,

211

api_version="2021-12-02", # API version to use

212

secondary_hostname="account-secondary.blob.core.windows.net", # Secondary endpoint

213

max_block_size=4*1024*1024, # 4MB max block size for uploads

214

max_single_put_size=64*1024*1024, # 64MB threshold for chunked uploads

215

min_large_block_upload_threshold=4*1024*1024+1, # Memory efficient threshold

216

use_byte_buffer=False, # Use byte buffer for block uploads

217

max_page_size=4*1024*1024, # 4MB max page size

218

max_single_get_size=32*1024*1024, # 32MB threshold for chunked downloads

219

max_chunk_get_size=4*1024*1024, # 4MB chunk size for downloads

220

audience="https://storage.azure.com/" # Azure AD audience

221

)

222

```

223

224

### Retry Policies

225

226

Configure automatic retry behavior for failed requests with exponential or linear backoff strategies.

227

228

```python { .api }

229

class ExponentialRetry:

230

def __init__(self, initial_backoff: int = 15, increment_base: int = 3, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs):

231

"""

232

Exponential retry policy with increasing backoff intervals.

233

234

Args:

235

initial_backoff (int): Initial backoff interval in seconds (default: 15)

236

increment_base (int): Base to increment backoff after first retry (default: 3)

237

retry_total (int): Maximum number of retry attempts (default: 3)

238

retry_to_secondary (bool): Whether to retry to secondary endpoint (default: False)

239

random_jitter_range (int): Range in seconds for randomizing backoff (default: 3)

240

"""

241

242

class LinearRetry:

243

def __init__(self, backoff: int = 15, retry_total: int = 3, retry_to_secondary: bool = False, random_jitter_range: int = 3, **kwargs):

244

"""

245

Linear retry policy with fixed backoff intervals.

246

247

Args:

248

backoff (int): Fixed backoff interval in seconds between retries (default: 15)

249

retry_total (int): Maximum number of retry attempts (default: 3)

250

retry_to_secondary (bool): Whether to retry to secondary endpoint (default: False)

251

random_jitter_range (int): Range in seconds for randomizing backoff (default: 3)

252

"""

253

```

254

255

**Usage Example:**

256

```python

257

from azure.storage.blob import BlobServiceClient, ExponentialRetry

258

259

# Configure exponential retry with custom settings

260

retry_policy = ExponentialRetry(

261

initial_backoff=5,

262

increment_base=2,

263

retry_total=5,

264

random_jitter_range=2

265

)

266

267

client = BlobServiceClient(

268

account_url="https://mystorageaccount.blob.core.windows.net",

269

credential="account_key_here",

270

retry_policy=retry_policy

271

)

272

```

273

274

### Error Handling

275

276

Azure Storage Blob provides specific error codes and exception classes for comprehensive error handling and troubleshooting.

277

278

```python { .api }

279

class StorageErrorCode:

280

"""Error codes returned by Azure Storage services."""

281

282

# Authentication and Authorization

283

AUTHENTICATION_FAILED: str = "AuthenticationFailed"

284

AUTHORIZATION_FAILURE: str = "AuthorizationFailure"

285

INSUFFICIENT_ACCOUNT_PERMISSIONS: str = "InsufficientAccountPermissions"

286

ACCOUNT_IS_DISABLED: str = "AccountIsDisabled"

287

288

# Condition Errors

289

CONDITION_NOT_MET: str = "ConditionNotMet"

290

CONDITION_HEADERS_NOT_SUPPORTED: str = "ConditionHeadersNotSupported"

291

292

# Resource Errors

293

RESOURCE_NOT_FOUND: str = "ResourceNotFound"

294

RESOURCE_ALREADY_EXISTS: str = "ResourceAlreadyExists"

295

CONTAINER_NOT_FOUND: str = "ContainerNotFound"

296

BLOB_NOT_FOUND: str = "BlobNotFound"

297

298

# Request Errors

299

INVALID_RANGE: str = "InvalidRange"

300

INVALID_INPUT: str = "InvalidInput"

301

INVALID_METADATA: str = "InvalidMetadata"

302

INVALID_HEADER_VALUE: str = "InvalidHeaderValue"

303

MD5_MISMATCH: str = "Md5Mismatch"

304

305

# Server Errors

306

INTERNAL_ERROR: str = "InternalError"

307

SERVER_BUSY: str = "ServerBusy"

308

309

class PartialBatchErrorException(HttpResponseError):

310

"""Exception raised when there is a partial failure in batch operations."""

311

312

def __init__(self, message: str, response, parts: list):

313

"""

314

Initialize PartialBatchErrorException.

315

316

Args:

317

message (str): Error message describing the exception

318

response: HTTP response object from the failed request

319

parts (list): List of the parts in multipart response that failed

320

"""

321

self.parts = parts

322

```

323

324

**Usage Example:**

325

```python

326

from azure.storage.blob import BlobServiceClient, StorageErrorCode

327

from azure.core.exceptions import HttpResponseError

328

329

try:

330

client = BlobServiceClient.from_connection_string(conn_str)

331

blob_client = client.get_blob_client("container", "nonexistent-blob")

332

properties = blob_client.get_blob_properties()

333

except HttpResponseError as e:

334

if e.error_code == StorageErrorCode.BLOB_NOT_FOUND:

335

print("Blob does not exist")

336

elif e.error_code == StorageErrorCode.CONTAINER_NOT_FOUND:

337

print("Container does not exist")

338

else:

339

print(f"Unexpected error: {e.error_code}")

340

```

341

342

## Supporting Data Types

343

344

```python { .api }

345

class BlobAnalyticsLogging:

346

"""Analytics logging configuration."""

347

version: str

348

delete: bool

349

read: bool

350

write: bool

351

retention_policy: RetentionPolicy

352

353

class Metrics:

354

"""Service metrics configuration."""

355

version: str

356

enabled: bool

357

include_apis: bool

358

retention_policy: RetentionPolicy

359

360

class RetentionPolicy:

361

"""Data retention policy."""

362

enabled: bool

363

days: int

364

365

class StaticWebsite:

366

"""Static website hosting configuration."""

367

enabled: bool

368

index_document: str

369

error_document404_path: str

370

default_index_document_path: str

371

372

class CorsRule:

373

"""Cross-origin resource sharing rule."""

374

allowed_origins: list[str]

375

allowed_methods: list[str]

376

allowed_headers: list[str]

377

exposed_headers: list[str]

378

max_age_in_seconds: int

379

380

class ContainerProperties:

381

"""Container properties returned by list operations."""

382

name: str

383

last_modified: datetime

384

etag: str

385

lease: LeaseProperties

386

public_access: PublicAccess

387

has_immutability_policy: bool

388

deleted: bool

389

version: str

390

has_legal_hold: bool

391

metadata: dict

392

encryption_scope: ContainerEncryptionScope

393

immutable_storage_with_versioning_enabled: bool

394

395

class UserDelegationKey:

396

"""User delegation key for SAS generation."""

397

signed_oid: str

398

signed_tid: str

399

signed_start: datetime

400

signed_expiry: datetime

401

signed_service: str

402

signed_version: str

403

value: str

404

405

class FilteredBlob:

406

"""Blob found by tag filtering."""

407

name: str

408

container_name: str

409

tag_value: str

410

```