0
# ShareServiceClient - Account-Level Operations
1
2
The ShareServiceClient is the entry point for managing Azure File Share operations at the storage account level. It provides methods to configure service properties, manage shares, and obtain clients for specific shares.
3
4
## Import and Initialization
5
6
```python { .api }
7
from azure.storage.fileshare import ShareServiceClient
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 ShareServiceClient:
16
def __init__(
17
self,
18
account_url: str,
19
credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
20
*,
21
token_intent: Optional[Literal['backup']] = None,
22
**kwargs: Any
23
) -> None:
24
"""
25
Create a ShareServiceClient from account URL and credentials.
26
27
Parameters:
28
account_url: The URL to the file service endpoint
29
credential: Authentication credential (key, SAS token, or Azure credential)
30
token_intent: Specifies the intent for all requests when using TokenCredential authentication
31
**kwargs: Additional client configuration options
32
"""
33
```
34
35
## Class Methods
36
37
```python { .api }
38
@classmethod
39
def from_connection_string(
40
cls,
41
conn_str: str,
42
credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,
43
**kwargs: Any
44
) -> ShareServiceClient:
45
"""
46
Create ShareServiceClient from connection string.
47
48
Parameters:
49
conn_str: Azure Storage connection string
50
credential: Optional credential to override connection string auth
51
**kwargs: Additional client configuration options
52
53
Returns:
54
ShareServiceClient: Configured service client instance
55
"""
56
```
57
58
## Service Properties Management
59
60
```python { .api }
61
def get_service_properties(
62
self,
63
**kwargs: Any
64
) -> Dict[str, Any]:
65
"""
66
Gets the properties of a storage account's File Share service.
67
68
Parameters:
69
timeout: Request timeout in seconds
70
71
Returns:
72
Dict containing service properties including:
73
- hour_metrics: Metrics configuration for hourly stats
74
- minute_metrics: Metrics configuration for minute stats
75
- cors: List of CORS rules
76
- protocol: Protocol settings (SMB settings)
77
"""
78
79
def set_service_properties(
80
self,
81
hour_metrics: Optional[Metrics] = None,
82
minute_metrics: Optional[Metrics] = None,
83
cors: Optional[List[CorsRule]] = None,
84
protocol: Optional[ShareProtocolSettings] = None,
85
**kwargs: Any
86
) -> None:
87
"""
88
Sets the properties of a storage account's File Share service.
89
90
Parameters:
91
hour_metrics: Metrics configuration for hourly aggregated statistics
92
minute_metrics: Metrics configuration for minute aggregated statistics
93
cors: Cross-origin resource sharing rules
94
protocol: Protocol-specific settings (SMB configuration)
95
timeout: Request timeout in seconds
96
"""
97
```
98
99
## Share Management
100
101
```python { .api }
102
def list_shares(
103
self,
104
name_starts_with: Optional[str] = None,
105
include_metadata: Optional[bool] = False,
106
include_snapshots: Optional[bool] = False,
107
**kwargs: Any
108
) -> ItemPaged[ShareProperties]:
109
"""
110
Returns an auto-paging iterable of ShareProperties under the account.
111
112
Parameters:
113
name_starts_with: Filter shares by name prefix
114
include_metadata: Include share metadata in results
115
include_snapshots: Include share snapshots in results
116
results_per_page: Number of shares per page
117
timeout: Request timeout in seconds
118
119
Returns:
120
ItemPaged[ShareProperties]: Paginated list of share properties
121
"""
122
123
def create_share(
124
self,
125
share_name: str,
126
**kwargs: Any
127
) -> ShareClient:
128
"""
129
Creates a new share under the specified account.
130
131
Parameters:
132
share_name: Name of the share to create
133
metadata: Optional dict of name-value pairs for share metadata
134
quota: Share size quota in GB (1-102400 for standard, 100-102400 for premium)
135
access_tier: Access tier for the share ("Hot", "Cool", "TransactionOptimized", "Premium")
136
protocols: Enabled protocols ("SMB", "NFS", or both)
137
root_squash: Root squash setting for NFS ("NoRootSquash", "RootSquash", "AllSquash")
138
timeout: Request timeout in seconds
139
140
Returns:
141
ShareClient: Client for the newly created share
142
"""
143
144
def delete_share(
145
self,
146
share_name: Union[ShareProperties, str],
147
delete_snapshots: Optional[bool] = False,
148
**kwargs: Any
149
) -> None:
150
"""
151
Marks the specified share for deletion.
152
153
Parameters:
154
share_name: Share to delete (name or ShareProperties object)
155
delete_snapshots: Whether to delete share snapshots
156
timeout: Request timeout in seconds
157
"""
158
159
def undelete_share(
160
self,
161
deleted_share_name: str,
162
deleted_share_version: str,
163
**kwargs: Any
164
) -> ShareClient:
165
"""
166
Restores soft-deleted share.
167
168
Parameters:
169
deleted_share_name: Name of the deleted share
170
deleted_share_version: Version of the deleted share to restore
171
timeout: Request timeout in seconds
172
173
Returns:
174
ShareClient: Client for the restored share
175
"""
176
```
177
178
## Client Factory Methods
179
180
```python { .api }
181
def get_share_client(
182
self,
183
share: Union[ShareProperties, str],
184
snapshot: Optional[Union[Dict[str, Any], str]] = None
185
) -> ShareClient:
186
"""
187
Get a client to interact with the specified share.
188
189
Parameters:
190
share: Share name or ShareProperties object
191
snapshot: Optional snapshot identifier
192
193
Returns:
194
ShareClient: Client configured for the specified share
195
"""
196
```
197
198
## Properties
199
200
```python { .api }
201
@property
202
def url(self) -> str:
203
"""The full endpoint URL to the file service."""
204
205
@property
206
def account_name(self) -> str:
207
"""The storage account name."""
208
209
@property
210
def credential(self) -> Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]:
211
"""The credential used to authenticate."""
212
213
@property
214
def api_version(self) -> str:
215
"""The Storage API version being used."""
216
```
217
218
## Usage Examples
219
220
### Basic Service Client Setup
221
222
```python { .api }
223
from azure.storage.fileshare import ShareServiceClient
224
from azure.core.credentials import AzureNamedKeyCredential
225
226
# Method 1: Connection string
227
service_client = ShareServiceClient.from_connection_string(
228
"DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net"
229
)
230
231
# Method 2: Account URL + credentials
232
credential = AzureNamedKeyCredential("myaccount", "mykey")
233
service_client = ShareServiceClient(
234
account_url="https://myaccount.file.core.windows.net",
235
credential=credential
236
)
237
238
# Method 3: SAS token
239
service_client = ShareServiceClient(
240
account_url="https://myaccount.file.core.windows.net",
241
credential="?sv=2021-06-08&ss=f&srt=sco&sp=rwdlacup&se=..."
242
)
243
```
244
245
### Managing Service Properties
246
247
```python { .api }
248
from azure.storage.fileshare import Metrics, CorsRule, ShareProtocolSettings, ShareSmbSettings, SmbMultichannel
249
250
# Configure metrics
251
hour_metrics = Metrics(
252
enabled=True,
253
include_apis=True,
254
retention_policy={"enabled": True, "days": 7}
255
)
256
257
# Configure CORS
258
cors_rules = [
259
CorsRule(
260
allowed_origins=["https://mywebsite.com"],
261
allowed_methods=["GET", "PUT", "POST"],
262
allowed_headers=["x-ms-*"],
263
exposed_headers=["x-ms-*"],
264
max_age_in_seconds=3600
265
)
266
]
267
268
# Configure SMB protocol settings
269
smb_settings = ShareSmbSettings(
270
multichannel=SmbMultichannel(enabled=True)
271
)
272
protocol_settings = ShareProtocolSettings(smb=smb_settings)
273
274
# Set service properties
275
service_client.set_service_properties(
276
hour_metrics=hour_metrics,
277
cors=cors_rules,
278
protocol=protocol_settings
279
)
280
281
# Get current properties
282
properties = service_client.get_service_properties()
283
print(f"Hour metrics enabled: {properties['hour_metrics']['enabled']}")
284
print(f"CORS rules: {len(properties['cors'])}")
285
```
286
287
### Share Lifecycle Management
288
289
```python { .api }
290
from azure.storage.fileshare import ShareProtocols
291
292
# Create a standard share with 100GB quota
293
share_client = service_client.create_share(
294
share_name="documents",
295
quota=100,
296
metadata={"environment": "production", "department": "finance"}
297
)
298
299
# Create a premium share with higher performance
300
premium_share = service_client.create_share(
301
share_name="high-performance",
302
quota=100,
303
access_tier="Premium",
304
protocols=[ShareProtocols.SMB]
305
)
306
307
# Create NFS share (requires premium account)
308
nfs_share = service_client.create_share(
309
share_name="nfs-share",
310
protocols=[ShareProtocols.NFS],
311
root_squash="NoRootSquash"
312
)
313
314
# List all shares with metadata
315
shares = list(service_client.list_shares(include_metadata=True, include_snapshots=True))
316
for share_props in shares:
317
print(f"Share: {share_props.name}")
318
print(f" Quota: {share_props.quota} GB")
319
print(f" Access Tier: {share_props.access_tier}")
320
print(f" Metadata: {share_props.metadata}")
321
if share_props.snapshot:
322
print(f" Snapshot: {share_props.snapshot}")
323
324
# Delete a share and its snapshots
325
service_client.delete_share("old-share", delete_snapshots=True)
326
```
327
328
### Advanced Share Operations
329
330
```python { .api }
331
# List shares with filtering
332
production_shares = list(service_client.list_shares(name_starts_with="prod-"))
333
334
# Restore a soft-deleted share
335
try:
336
restored_share = service_client.undelete_share("deleted-share", "version-id")
337
print(f"Restored share: {restored_share.share_name}")
338
except Exception as e:
339
print(f"Could not restore share: {e}")
340
341
# Get share client for further operations
342
share_client = service_client.get_share_client("documents")
343
snapshot_client = service_client.get_share_client("documents", snapshot="2023-01-01T00:00:00Z")
344
```
345
346
### Error Handling
347
348
```python { .api }
349
from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError, HttpResponseError
350
351
try:
352
# Attempt to create share
353
share_client = service_client.create_share("myshare")
354
except ResourceExistsError:
355
# Share already exists, get existing client
356
share_client = service_client.get_share_client("myshare")
357
except HttpResponseError as e:
358
if e.error_code == "ShareQuotaExceeded":
359
print("Account share limit exceeded")
360
else:
361
print(f"Failed to create share: {e.message}")
362
363
try:
364
# Attempt to delete share
365
service_client.delete_share("nonexistent-share")
366
except ResourceNotFoundError:
367
print("Share not found for deletion")
368
```
369
370
### Configuration Options
371
372
```python { .api }
373
# Service client with custom configuration
374
service_client = ShareServiceClient.from_connection_string(
375
conn_str,
376
connection_timeout=30, # Connection timeout in seconds
377
read_timeout=60, # Read timeout in seconds
378
max_range_size=4*1024*1024, # 4MB range size for operations
379
max_single_put_size=64*1024*1024, # 64MB max single upload
380
retry_total=3, # Number of retry attempts
381
retry_backoff_factor=0.4, # Exponential backoff factor
382
transport=transport # Custom HTTP transport
383
)
384
```
385
386
The ShareServiceClient provides comprehensive account-level management capabilities for Azure File Shares. Use it as the entry point to create and manage shares, configure service-wide settings, and obtain clients for specific share operations.