0
# ShareClient - Share-Level Operations
1
2
The ShareClient provides operations for managing individual file shares, including creating snapshots, managing quotas, setting permissions, and performing directory and file operations at the share root level.
3
4
## Import and Initialization
5
6
```python { .api }
7
from azure.storage.fileshare import ShareClient, ShareLeaseClient
8
from azure.core.credentials import AzureNamedKeyCredential
9
from typing import Optional, Union, Dict, Any, List
10
```
11
12
## Constructor
13
14
```python { .api }
15
class ShareClient:
16
def __init__(
17
self,
18
account_url: str,
19
share_name: str,
20
snapshot: Optional[str] = None,
21
credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
22
*,
23
token_intent: Optional[Literal['backup']] = None,
24
**kwargs: Any
25
) -> None:
26
"""
27
Create a ShareClient for a specific share.
28
29
Parameters:
30
account_url: The URL to the file service endpoint
31
share_name: Name of the share
32
snapshot: Optional share snapshot identifier
33
credential: Authentication credential
34
token_intent: Specifies the intent for all requests when using TokenCredential authentication
35
**kwargs: Additional client configuration options
36
"""
37
```
38
39
## Class Methods
40
41
```python { .api }
42
@classmethod
43
def from_share_url(
44
cls,
45
share_url: str,
46
credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
47
**kwargs: Any
48
) -> ShareClient:
49
"""
50
Create ShareClient from share URL.
51
52
Parameters:
53
share_url: Complete URL to the share
54
credential: Authentication credential
55
**kwargs: Additional client configuration options
56
57
Returns:
58
ShareClient: Configured client instance
59
"""
60
61
@classmethod
62
def from_connection_string(
63
cls,
64
conn_str: str,
65
share_name: str,
66
snapshot: Optional[str] = None,
67
credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
68
**kwargs: Any
69
) -> ShareClient:
70
"""
71
Create ShareClient from connection string.
72
73
Parameters:
74
conn_str: Azure Storage connection string
75
share_name: Name of the share
76
snapshot: Optional share snapshot identifier
77
credential: Optional credential to override connection string auth
78
**kwargs: Additional client configuration options
79
80
Returns:
81
ShareClient: Configured client instance
82
"""
83
```
84
85
## Client Factory Methods
86
87
```python { .api }
88
def get_directory_client(
89
self,
90
directory_path: Optional[str] = None
91
) -> ShareDirectoryClient:
92
"""
93
Get a client to interact with the specified directory.
94
95
Parameters:
96
directory_path: Path to the directory (None for root directory)
97
98
Returns:
99
ShareDirectoryClient: Client configured for the directory
100
"""
101
102
def get_file_client(
103
self,
104
file_path: str
105
) -> ShareFileClient:
106
"""
107
Get a client to interact with the specified file.
108
109
Parameters:
110
file_path: Path to the file from share root
111
112
Returns:
113
ShareFileClient: Client configured for the file
114
"""
115
```
116
117
## Share Lifecycle Operations
118
119
```python { .api }
120
def create_share(
121
self,
122
**kwargs: Any
123
) -> Dict[str, Any]:
124
"""
125
Creates a new share under the account.
126
127
Parameters:
128
metadata: Dict of name-value pairs for share metadata
129
quota: Share size quota in GB (1-102400 for standard accounts)
130
access_tier: Access tier ("Hot", "Cool", "TransactionOptimized", "Premium")
131
protocols: Enabled protocols (list of "SMB", "NFS")
132
root_squash: Root squash setting for NFS ("NoRootSquash", "RootSquash", "AllSquash")
133
timeout: Request timeout in seconds
134
135
Returns:
136
Dict containing share creation response with ETag and last modified time
137
"""
138
139
def delete_share(
140
self,
141
delete_snapshots: Optional[bool] = False,
142
**kwargs: Any
143
) -> None:
144
"""
145
Marks the specified share for deletion.
146
147
Parameters:
148
delete_snapshots: Whether to delete share snapshots
149
lease_id: Required if share has an active lease
150
if_modified_since: Delete only if modified since specified time
151
if_unmodified_since: Delete only if not modified since specified time
152
if_match: Delete only if ETag matches
153
if_none_match: Delete only if ETag does not match
154
timeout: Request timeout in seconds
155
"""
156
157
def create_snapshot(
158
self,
159
**kwargs: Any
160
) -> Dict[str, Any]:
161
"""
162
Creates a snapshot of the share.
163
164
Parameters:
165
metadata: Dict of name-value pairs for snapshot metadata
166
timeout: Request timeout in seconds
167
168
Returns:
169
Dict containing snapshot information including snapshot ID and ETag
170
"""
171
```
172
173
## Share Properties and Metadata
174
175
```python { .api }
176
def get_share_properties(
177
self,
178
**kwargs: Any
179
) -> ShareProperties:
180
"""
181
Returns all user-defined metadata and system properties for the share.
182
183
Parameters:
184
timeout: Request timeout in seconds
185
186
Returns:
187
ShareProperties: Object containing all share properties
188
"""
189
190
def set_share_quota(
191
self,
192
quota: int,
193
**kwargs: Any
194
) -> Dict[str, Any]:
195
"""
196
Sets the quota for the share.
197
198
Parameters:
199
quota: Share size limit in GB (1-102400 for standard accounts)
200
timeout: Request timeout in seconds
201
202
Returns:
203
Dict containing response with ETag and last modified time
204
"""
205
206
def set_share_properties(
207
self,
208
**kwargs: Any
209
) -> Dict[str, Any]:
210
"""
211
Sets share properties.
212
213
Parameters:
214
access_tier: Share access tier ("Hot", "Cool", "TransactionOptimized", "Premium")
215
quota: Share size quota in GB
216
root_squash: Root squash setting for NFS shares
217
timeout: Request timeout in seconds
218
219
Returns:
220
Dict containing response with ETag and last modified time
221
"""
222
223
def set_share_metadata(
224
self,
225
metadata: Dict[str, str],
226
**kwargs: Any
227
) -> Dict[str, Any]:
228
"""
229
Sets user-defined metadata for the share.
230
231
Parameters:
232
metadata: Dict of name-value pairs (keys must be valid metadata names)
233
timeout: Request timeout in seconds
234
235
Returns:
236
Dict containing response with ETag and last modified time
237
"""
238
```
239
240
## Access Control and Permissions
241
242
```python { .api }
243
def get_share_access_policy(
244
self,
245
**kwargs: Any
246
) -> Dict[str, Any]:
247
"""
248
Gets the permissions for the share.
249
250
Parameters:
251
timeout: Request timeout in seconds
252
253
Returns:
254
Dict containing signed identifiers with their access policies
255
"""
256
257
def set_share_access_policy(
258
self,
259
signed_identifiers: Dict[str, AccessPolicy],
260
**kwargs: Any
261
) -> Dict[str, Any]:
262
"""
263
Sets the permissions for the share.
264
265
Parameters:
266
signed_identifiers: Dict mapping policy IDs to AccessPolicy objects
267
timeout: Request timeout in seconds
268
269
Returns:
270
Dict containing response with ETag and last modified time
271
"""
272
273
def create_permission_for_share(
274
self,
275
file_permission: str,
276
**kwargs: Any
277
) -> Optional[str]:
278
"""
279
Create a permission (security descriptor) at the share level.
280
281
Parameters:
282
file_permission: Security descriptor string in SDDL format
283
timeout: Request timeout in seconds
284
285
Returns:
286
Optional[str]: Permission key that can be used to reference this permission
287
"""
288
289
def get_permission_for_share(
290
self,
291
permission_key: str,
292
**kwargs: Any
293
) -> str:
294
"""
295
Get a permission (security descriptor) for a given key.
296
297
Parameters:
298
permission_key: Key returned from create_permission_for_share
299
timeout: Request timeout in seconds
300
301
Returns:
302
str: Security descriptor string in SDDL format
303
"""
304
```
305
306
## Share Statistics
307
308
```python { .api }
309
def get_share_stats(
310
self,
311
**kwargs: Any
312
) -> int:
313
"""
314
Gets the approximate size of the data stored on the share.
315
316
Parameters:
317
timeout: Request timeout in seconds
318
319
Returns:
320
int: Size of share content in bytes
321
"""
322
```
323
324
## Directory and File Management
325
326
```python { .api }
327
def list_directories_and_files(
328
self,
329
directory_name: Optional[str] = None,
330
name_starts_with: Optional[str] = None,
331
marker: Optional[str] = None,
332
**kwargs: Any
333
) -> ItemPaged[Dict[str, Any]]:
334
"""
335
Lists directories and files under the share.
336
337
Parameters:
338
directory_name: Directory path to list (None for root)
339
name_starts_with: Filter by name prefix
340
marker: Continuation token for pagination
341
results_per_page: Maximum items per page
342
timeout: Request timeout in seconds
343
344
Returns:
345
ItemPaged[Dict]: Paginated list of directory/file info dicts
346
"""
347
348
def create_directory(
349
self,
350
directory_name: str,
351
**kwargs: Any
352
) -> ShareDirectoryClient:
353
"""
354
Creates a directory in the share.
355
356
Parameters:
357
directory_name: Name/path of the directory to create
358
metadata: Dict of name-value pairs for directory metadata
359
timeout: Request timeout in seconds
360
361
Returns:
362
ShareDirectoryClient: Client for the newly created directory
363
"""
364
365
def delete_directory(
366
self,
367
directory_name: str,
368
**kwargs: Any
369
) -> None:
370
"""
371
Deletes the specified directory.
372
373
Parameters:
374
directory_name: Name/path of the directory to delete
375
timeout: Request timeout in seconds
376
"""
377
```
378
379
## Lease Management
380
381
```python { .api }
382
def acquire_lease(
383
self,
384
**kwargs: Any
385
) -> ShareLeaseClient:
386
"""
387
Requests a new lease for the share.
388
389
Parameters:
390
lease_duration: Duration of the lease in seconds (-1 for infinite)
391
lease_id: Proposed lease ID (UUID format)
392
timeout: Request timeout in seconds
393
394
Returns:
395
ShareLeaseClient: Lease client for managing the lease
396
"""
397
```
398
399
## Properties
400
401
```python { .api }
402
@property
403
def url(self) -> str:
404
"""The full endpoint URL to the share."""
405
406
@property
407
def share_name(self) -> str:
408
"""The name of the share with which to interact."""
409
410
@property
411
def snapshot(self) -> Optional[str]:
412
"""An optional share snapshot on which to operate."""
413
414
@property
415
def account_name(self) -> str:
416
"""The storage account name."""
417
418
@property
419
def credential(self) -> Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]:
420
"""The credential used to authenticate."""
421
```
422
423
## Usage Examples
424
425
### Basic Share Operations
426
427
```python { .api }
428
from azure.storage.fileshare import ShareClient
429
from azure.core.credentials import AzureNamedKeyCredential
430
431
# Initialize client
432
credential = AzureNamedKeyCredential("myaccount", "mykey")
433
share_client = ShareClient(
434
account_url="https://myaccount.file.core.windows.net",
435
share_name="documents",
436
credential=credential
437
)
438
439
# Create share with properties
440
response = share_client.create_share(
441
quota=100,
442
access_tier="Hot",
443
metadata={"environment": "production", "department": "finance"}
444
)
445
print(f"Share created with ETag: {response['etag']}")
446
447
# Get share properties
448
properties = share_client.get_share_properties()
449
print(f"Share quota: {properties.quota} GB")
450
print(f"Last modified: {properties.last_modified}")
451
print(f"Metadata: {properties.metadata}")
452
```
453
454
### Share Configuration Management
455
456
```python { .api }
457
# Update share quota
458
share_client.set_share_quota(200) # Increase to 200 GB
459
460
# Set share properties
461
share_client.set_share_properties(
462
access_tier="Cool", # Change to cooler tier for cost savings
463
quota=150
464
)
465
466
# Update metadata
467
share_client.set_share_metadata({
468
"environment": "production",
469
"cost_center": "12345",
470
"retention_policy": "7years"
471
})
472
473
# Get share statistics
474
used_space = share_client.get_share_stats()
475
properties = share_client.get_share_properties()
476
print(f"Share usage: {used_space / (1024**3):.2f} GB of {properties.quota} GB")
477
```
478
479
### Snapshot Management
480
481
```python { .api }
482
from datetime import datetime
483
484
# Create snapshot with metadata
485
snapshot_response = share_client.create_snapshot(
486
metadata={"backup_date": datetime.now().isoformat()}
487
)
488
snapshot_id = snapshot_response['snapshot']
489
print(f"Snapshot created: {snapshot_id}")
490
491
# Work with snapshot
492
snapshot_client = ShareClient(
493
account_url="https://myaccount.file.core.windows.net",
494
share_name="documents",
495
snapshot=snapshot_id,
496
credential=credential
497
)
498
499
# List files in snapshot
500
snapshot_items = list(snapshot_client.list_directories_and_files())
501
print(f"Snapshot contains {len(snapshot_items)} items")
502
```
503
504
### Access Policy Management
505
506
```python { .api }
507
from azure.storage.fileshare import AccessPolicy, ShareSasPermissions
508
from datetime import datetime, timedelta
509
510
# Define access policies
511
read_policy = AccessPolicy(
512
permission=ShareSasPermissions(read=True, list=True),
513
expiry=datetime.utcnow() + timedelta(days=30),
514
start=datetime.utcnow()
515
)
516
517
write_policy = AccessPolicy(
518
permission=ShareSasPermissions(read=True, write=True, create=True, delete=True),
519
expiry=datetime.utcnow() + timedelta(hours=24),
520
start=datetime.utcnow()
521
)
522
523
# Set access policies
524
share_client.set_share_access_policy({
525
"readonly": read_policy,
526
"fullaccess": write_policy
527
})
528
529
# Get current policies
530
policies = share_client.get_share_access_policy()
531
for policy_id, policy in policies.items():
532
print(f"Policy {policy_id}: expires {policy['expiry']}")
533
```
534
535
### Permission Management (Windows ACLs)
536
537
```python { .api }
538
# Create a security descriptor for Windows ACL
539
sddl = "O:BAG:BAD:(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;BU)"
540
permission_key = share_client.create_permission_for_share(sddl)
541
print(f"Permission created with key: {permission_key}")
542
543
# Retrieve permission by key
544
retrieved_permission = share_client.get_permission_for_share(permission_key)
545
print(f"Retrieved permission: {retrieved_permission}")
546
```
547
548
### Directory and File Operations
549
550
```python { .api }
551
# Create directories
552
documents_dir = share_client.create_directory("documents")
553
reports_dir = share_client.create_directory("reports/quarterly")
554
555
# List root contents
556
root_items = list(share_client.list_directories_and_files())
557
for item in root_items:
558
item_type = "Directory" if item.get('is_directory') else "File"
559
print(f"{item_type}: {item['name']}")
560
561
# Filter by prefix
562
pdf_files = list(share_client.list_directories_and_files(
563
name_starts_with="report"
564
))
565
566
# Get clients for further operations
567
file_client = share_client.get_file_client("document.pdf")
568
directory_client = share_client.get_directory_client("documents")
569
```
570
571
### Lease Management
572
573
```python { .api }
574
# Acquire a lease on the share
575
lease_client = share_client.acquire_lease(lease_duration=60) # 60 second lease
576
print(f"Lease acquired with ID: {lease_client.id}")
577
578
# Use lease for operations
579
try:
580
share_client.set_share_metadata(
581
{"locked_by": "batch_process"},
582
lease_id=lease_client.id
583
)
584
585
# Perform operations while lease is held
586
# ...
587
588
finally:
589
# Always release the lease
590
lease_client.release()
591
```
592
593
### Error Handling and Validation
594
595
```python { .api }
596
from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError, HttpResponseError
597
598
try:
599
# Attempt share creation
600
share_client.create_share(quota=50)
601
except ResourceExistsError:
602
print("Share already exists, checking properties...")
603
properties = share_client.get_share_properties()
604
print(f"Existing quota: {properties.quota} GB")
605
606
try:
607
# Try to get non-existent permission
608
permission = share_client.get_permission_for_share("invalid-key")
609
except HttpResponseError as e:
610
if e.error_code == "SharePermissionNotFound":
611
print("Permission key not found")
612
else:
613
raise
614
615
# Validate quota limits
616
properties = share_client.get_share_properties()
617
if properties.quota < 100:
618
share_client.set_share_quota(100)
619
print("Quota increased to minimum required size")
620
```
621
622
The ShareClient provides comprehensive management capabilities for individual file shares, enabling you to configure properties, manage access control, create snapshots, and perform directory/file operations at the share level.