0
# Azure Storage File Share Python SDK
1
2
## Overview
3
4
Azure Storage File Share provides fully managed file shares in the cloud that are accessible via the industry standard Server Message Block (SMB) protocol or Network File System (NFS) protocol. The Azure Storage File Share Python SDK (`azure-storage-file-share`) enables developers to programmatically interact with Azure File Shares using Python applications.
5
6
Key capabilities include:
7
- **Account-level operations**: Manage service properties, list/create/delete shares
8
- **Share-level operations**: Create snapshots, set quotas, manage permissions and metadata
9
- **Directory operations**: Create/delete directories, list contents, manage metadata
10
- **File operations**: Upload/download files, copy operations, range management, lease management
11
- **Advanced features**: SAS token generation, async support, handle management, symbolic links
12
13
## Package Information
14
15
- **Package Name**: azure-storage-file-share
16
- **Package Type**: pypi
17
- **Language**: Python
18
- **Installation**: `pip install azure-storage-file-share`
19
20
## Core Imports
21
22
```python { .api }
23
# Main synchronous clients
24
from azure.storage.fileshare import (
25
ShareServiceClient,
26
ShareClient,
27
ShareDirectoryClient,
28
ShareFileClient,
29
ShareLeaseClient
30
)
31
32
# Async clients
33
from azure.storage.fileshare.aio import (
34
ShareServiceClient as AsyncShareServiceClient,
35
ShareClient as AsyncShareClient,
36
ShareDirectoryClient as AsyncShareDirectoryClient,
37
ShareFileClient as AsyncShareFileClient,
38
ShareLeaseClient as AsyncShareLeaseClient
39
)
40
41
# SAS generation functions
42
from azure.storage.fileshare import (
43
generate_account_sas,
44
generate_share_sas,
45
generate_file_sas
46
)
47
48
# Models and properties
49
from azure.storage.fileshare import (
50
ShareProperties,
51
FileProperties,
52
DirectoryProperties,
53
ContentSettings,
54
Handle,
55
Metrics,
56
RetentionPolicy,
57
CorsRule,
58
ShareSmbSettings,
59
ShareAccessTier,
60
SmbMultichannel,
61
ShareProtocolSettings,
62
AccessPolicy,
63
ShareSasPermissions,
64
FileSasPermissions,
65
NTFSAttributes,
66
ShareProtocols,
67
ShareRootSquash
68
)
69
70
# Retry policies and shared models
71
from azure.storage.fileshare import (
72
ExponentialRetry,
73
LinearRetry,
74
LocationMode,
75
ResourceTypes,
76
AccountSasPermissions,
77
StorageErrorCode,
78
Services
79
)
80
81
# Credentials and authentication
82
from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential
83
```
84
85
## Basic Usage
86
87
### Client Authentication Options
88
89
```python { .api }
90
from azure.storage.fileshare import ShareServiceClient
91
from azure.core.credentials import AzureNamedKeyCredential
92
93
# Option 1: Connection string (recommended for development)
94
service_client = ShareServiceClient.from_connection_string(
95
conn_str="DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=mykey;EndpointSuffix=core.windows.net"
96
)
97
98
# Option 2: Account URL + Named Key Credential
99
credential = AzureNamedKeyCredential("myaccount", "mykey")
100
service_client = ShareServiceClient(
101
account_url="https://myaccount.file.core.windows.net",
102
credential=credential
103
)
104
105
# Option 3: SAS token
106
service_client = ShareServiceClient(
107
account_url="https://myaccount.file.core.windows.net",
108
credential="?sv=2021-06-08&ss=f&srt=sco&sp=rwdlacup&se=..."
109
)
110
111
# Option 4: Azure Active Directory (OAuth)
112
from azure.identity import DefaultAzureCredential
113
credential = DefaultAzureCredential()
114
service_client = ShareServiceClient(
115
account_url="https://myaccount.file.core.windows.net",
116
credential=credential
117
)
118
```
119
120
### Common Operations
121
122
```python { .api }
123
# Create a file share
124
share_client = service_client.create_share("myshare", quota=100) # 100 GB quota
125
126
# Get clients for specific resources
127
directory_client = share_client.get_directory_client("mydirectory")
128
file_client = share_client.get_file_client("myfile.txt")
129
130
# Upload a file
131
with open("local_file.txt", "rb") as data:
132
file_client.upload_file(data, overwrite=True)
133
134
# Download a file
135
download_stream = file_client.download_file()
136
with open("downloaded_file.txt", "wb") as file_handle:
137
download_stream.readinto(file_handle)
138
139
# List shares
140
shares = list(service_client.list_shares(include_metadata=True))
141
for share in shares:
142
print(f"Share: {share.name}, Quota: {share.quota} GB")
143
144
# Create directory structure
145
directory_client.create_directory()
146
subdirectory_client = directory_client.create_subdirectory("subdir")
147
148
# List directory contents
149
items = list(directory_client.list_directories_and_files())
150
for item in items:
151
print(f"{'Directory' if item.get('is_directory') else 'File'}: {item['name']}")
152
```
153
154
### Async Usage Pattern
155
156
```python { .api }
157
import asyncio
158
from azure.storage.fileshare.aio import ShareServiceClient
159
160
async def main():
161
async with ShareServiceClient.from_connection_string(conn_str) as service_client:
162
# Create share
163
share_client = await service_client.create_share("asyncshare")
164
165
# Upload file asynchronously
166
file_client = share_client.get_file_client("asyncfile.txt")
167
with open("local_file.txt", "rb") as data:
168
await file_client.upload_file(data)
169
170
# Download file asynchronously
171
download_stream = await file_client.download_file()
172
content = await download_stream.readall()
173
174
# List shares asynchronously
175
async for share in service_client.list_shares():
176
print(f"Share: {share.name}")
177
178
# Run async function
179
asyncio.run(main())
180
```
181
182
## Architecture
183
184
The Azure Storage File Share SDK follows a hierarchical client architecture:
185
186
```
187
ShareServiceClient (Account Level)
188
├── ShareClient (Share Level)
189
├── ShareDirectoryClient (Directory Level)
190
│ ├── ShareFileClient (File Level)
191
│ └── ShareDirectoryClient (Subdirectory)
192
└── ShareFileClient (Root File Level)
193
```
194
195
### Client Hierarchy
196
197
1. **ShareServiceClient**: Entry point for account-level operations
198
- Manage service properties and CORS rules
199
- List, create, and delete shares
200
- Generate account-level SAS tokens
201
202
2. **ShareClient**: Operations on a specific file share
203
- Create snapshots and manage quotas
204
- Set share-level permissions and metadata
205
- Create directories and files at the root level
206
207
3. **ShareDirectoryClient**: Operations on directories
208
- Create, delete, and list directory contents
209
- Manage directory metadata and properties
210
- Handle file operations within the directory
211
212
4. **ShareFileClient**: Operations on individual files
213
- Upload, download, copy files
214
- Manage file properties and metadata
215
- Handle range operations and leases
216
217
5. **ShareLeaseClient**: Lease management for files and shares
218
- Acquire, renew, release, and break leases
219
- Change lease IDs
220
221
### Client Factory Methods
222
223
```python { .api }
224
# Get clients from parent clients
225
share_client = service_client.get_share_client("myshare")
226
directory_client = share_client.get_directory_client("path/to/directory")
227
file_client = share_client.get_file_client("path/to/file.txt")
228
file_client = directory_client.get_file_client("filename.txt")
229
230
# Create from URLs
231
share_client = ShareClient.from_share_url("https://account.file.core.windows.net/share")
232
directory_client = ShareDirectoryClient.from_directory_url("https://account.file.core.windows.net/share/dir")
233
file_client = ShareFileClient.from_file_url("https://account.file.core.windows.net/share/file.txt")
234
235
# Create from connection strings
236
share_client = ShareClient.from_connection_string(conn_str, "sharename")
237
directory_client = ShareDirectoryClient.from_connection_string(conn_str, "share", "dir/path")
238
file_client = ShareFileClient.from_connection_string(conn_str, "share", "file/path.txt")
239
```
240
241
## Capabilities
242
243
### Account Management
244
- [Service Client Operations](service-client.md) - Account-level operations, service properties, share management
245
246
### Share Operations
247
- [Share Client Operations](share-client.md) - Share creation, snapshots, quotas, permissions, metadata
248
249
### Directory Management
250
- [Directory Client Operations](directory-client.md) - Directory CRUD, listing, metadata, handle management
251
252
### File Operations
253
- [File Client Operations](file-client.md) - File upload/download, properties, range operations, copying
254
255
### Lease Management
256
- [Lease Client Operations](lease-client.md) - File and share lease acquisition, renewal, release
257
258
### Security & Access Control
259
- [SAS Token Generation](sas-generation.md) - Shared Access Signature creation for secure access
260
261
### Async Programming
262
- [Async Client Operations](async-clients.md) - Asynchronous versions of all operations
263
264
### Data Models
265
- [Models and Properties](models.md) - Complete reference for all data structures and enums
266
267
### Key Features Summary
268
269
```python { .api }
270
# File Share Management
271
shares = service_client.list_shares(include_metadata=True)
272
share_client = service_client.create_share("myshare", quota=100)
273
snapshot = share_client.create_snapshot()
274
275
# File Operations
276
file_client.upload_file(data, overwrite=True, max_concurrency=4)
277
download_stream = file_client.download_file(offset=0, length=1024)
278
file_client.upload_range(data=b"chunk", offset=1024, length=len(data))
279
280
# Directory Management
281
directory_client.create_directory()
282
items = directory_client.list_directories_and_files(name_starts_with="prefix")
283
handles = directory_client.list_handles(recursive=True)
284
285
# Access Control & Security
286
sas_token = generate_share_sas(account_name, share_name, account_key,
287
permission="r", expiry=datetime.now() + timedelta(hours=1))
288
lease_client = file_client.acquire_lease()
289
290
# Metadata and Properties
291
share_client.set_share_metadata({"environment": "production"})
292
file_client.set_http_headers(ContentSettings(content_type="text/plain"))
293
properties = file_client.get_file_properties()
294
295
# Advanced Operations
296
file_client.copy_file_from_url(source_url)
297
file_client.resize_file(new_size=2048)
298
symlink_client = directory_client.create_symlink("link_name", "target_path")
299
```
300
301
### Error Handling
302
303
```python { .api }
304
from azure.core.exceptions import (
305
HttpResponseError,
306
ResourceNotFoundError,
307
ResourceExistsError,
308
ClientAuthenticationError
309
)
310
311
try:
312
file_client.upload_file(data)
313
except ResourceExistsError:
314
print("File already exists")
315
except ResourceNotFoundError:
316
print("Share or directory not found")
317
except ClientAuthenticationError:
318
print("Authentication failed")
319
except HttpResponseError as e:
320
print(f"HTTP error: {e.status_code} - {e.error_code}")
321
```
322
323
For complete API documentation, see the individual capability documents linked above.