0
# Models and Properties - Data Structures and Enums
1
2
The Azure Storage File Share SDK provides comprehensive data models and enums that represent file share properties, metadata, permissions, and various configuration options.
3
4
## Core Properties Classes
5
6
### ShareProperties
7
8
```python { .api }
9
from azure.storage.fileshare import ShareProperties
10
from datetime import datetime
11
from typing import Optional, Dict, List, Union
12
13
class ShareProperties:
14
"""Properties of a file share."""
15
16
name: str
17
"""The name of the share."""
18
19
last_modified: datetime
20
"""A datetime object representing the last time the share was modified."""
21
22
etag: str
23
"""The ETag contains a value for performing operations conditionally."""
24
25
quota: int
26
"""The allocated quota in GB."""
27
28
access_tier: Optional[str]
29
"""The share's access tier (Hot, Cool, TransactionOptimized, Premium)."""
30
31
next_allowed_quota_downgrade_time: Optional[str]
32
"""The share's next allowed quota downgrade time."""
33
34
metadata: Dict[str, str]
35
"""Name-value pairs associated with the share as metadata."""
36
37
snapshot: Optional[str]
38
"""Snapshot identifier if this represents a share snapshot."""
39
40
deleted: Optional[bool]
41
"""Whether this share was deleted (for soft-deleted shares)."""
42
43
deleted_time: Optional[datetime]
44
"""Time at which the share was deleted (for soft-deleted shares)."""
45
46
version: Optional[str]
47
"""Version identifier for deleted share."""
48
49
remaining_retention_days: Optional[int]
50
"""Number of days until permanent deletion (for soft-deleted shares)."""
51
52
provisioned_egress_mbps: Optional[int]
53
"""Provisioned egress in Mbps (premium file accounts only)."""
54
55
provisioned_ingress_mbps: Optional[int]
56
"""Provisioned ingress in Mbps (premium file accounts only)."""
57
58
provisioned_iops: Optional[int]
59
"""Provisioned IOPS (premium file accounts only)."""
60
61
provisioned_bandwidth: Optional[int]
62
"""Provisioned bandwidth in Mbps (premium file accounts only)."""
63
64
lease: LeaseProperties
65
"""Share lease properties."""
66
67
protocols: Optional[List[str]]
68
"""Enabled protocols (SMB, NFS)."""
69
70
root_squash: Optional[Union[ShareRootSquash, str]]
71
"""Root squash setting (NoRootSquash, RootSquash, AllSquash)."""
72
73
enable_snapshot_virtual_directory_access: Optional[bool]
74
"""Whether snapshot virtual directory is accessible at share mount point."""
75
76
paid_bursting_enabled: Optional[int]
77
"""Whether paid bursting is enabled."""
78
79
paid_bursting_bandwidth_mibps: Optional[int]
80
"""Maximum throughput with paid bursting in MiB/s."""
81
82
paid_bursting_iops: Optional[int]
83
"""Maximum IOPS with paid bursting."""
84
85
next_provisioned_iops_downgrade: Optional[datetime]
86
"""Next allowed provisioned IOPS downgrade time."""
87
88
next_provisioned_bandwidth_downgrade: Optional[datetime]
89
"""Next allowed provisioned bandwidth downgrade time."""
90
```
91
92
### FileProperties
93
94
```python { .api }
95
from azure.storage.fileshare import FileProperties, ContentSettings, CopyProperties, LeaseProperties
96
from azure.storage.fileshare import NTFSAttributes
97
98
class FileProperties:
99
"""Properties of a file."""
100
101
name: str
102
"""The name of the file."""
103
104
path: Optional[str]
105
"""The path of the file."""
106
107
share: Optional[str]
108
"""The name of the share containing the file."""
109
110
snapshot: Optional[str]
111
"""File snapshot identifier."""
112
113
content_length: int
114
"""Size of file in bytes."""
115
116
metadata: Dict[str, str]
117
"""Name-value pairs associated with the file as metadata."""
118
119
file_type: str
120
"""String indicating the type of file."""
121
122
last_modified: datetime
123
"""Last modification time of the file."""
124
125
etag: str
126
"""ETag for conditional operations."""
127
128
size: int
129
"""Size of the file in bytes."""
130
131
content_range: Optional[str]
132
"""Range of bytes returned for partial content requests."""
133
134
server_encrypted: bool
135
"""Whether encryption is enabled."""
136
137
copy: CopyProperties
138
"""Copy operation properties."""
139
140
content_settings: ContentSettings
141
"""HTTP content settings for the file."""
142
143
lease: LeaseProperties
144
"""File lease properties."""
145
146
change_time: Optional[Union[str, datetime]]
147
"""Change time for the file (Windows)."""
148
149
creation_time: Optional[Union[str, datetime]]
150
"""Creation time for the file (Windows)."""
151
152
last_write_time: Optional[Union[str, datetime]]
153
"""Last write time for the file (Windows)."""
154
155
last_access_time: Optional[datetime]
156
"""Last access time for the file."""
157
158
file_attributes: Union[str, NTFSAttributes]
159
"""File system attributes."""
160
161
permission_key: str
162
"""Key of the permission set for the file."""
163
164
file_id: str
165
"""Unique identifier for the file."""
166
167
parent_id: Optional[str]
168
"""Unique identifier of the parent directory."""
169
170
is_directory: bool
171
"""Whether this represents a directory (False for files)."""
172
173
owner: Optional[str]
174
"""NFS only - The owner of the file."""
175
176
group: Optional[str]
177
"""NFS only - The owning group of the file."""
178
179
file_mode: Optional[str]
180
"""NFS only - The file mode."""
181
182
link_count: Optional[int]
183
"""NFS only - Number of hard links."""
184
185
nfs_file_type: Optional[Literal['Regular']]
186
"""NFS only - The type of the file."""
187
```
188
189
### DirectoryProperties
190
191
```python { .api }
192
from azure.storage.fileshare import DirectoryProperties
193
194
class DirectoryProperties:
195
"""Properties of a directory."""
196
197
name: str
198
"""The name of the directory."""
199
200
last_modified: datetime
201
"""Last modification time of the directory."""
202
203
etag: str
204
"""ETag for conditional operations."""
205
206
server_encrypted: bool
207
"""Whether encryption is enabled."""
208
209
metadata: Dict[str, str]
210
"""Name-value pairs associated with the directory as metadata."""
211
212
change_time: Optional[Union[str, datetime]]
213
"""Change time for the directory (Windows)."""
214
215
creation_time: Optional[Union[str, datetime]]
216
"""Creation time for the directory (Windows)."""
217
218
last_write_time: Optional[Union[str, datetime]]
219
"""Last write time for the directory (Windows)."""
220
221
last_access_time: Optional[datetime]
222
"""Last access time for the directory."""
223
224
file_attributes: Union[str, NTFSAttributes]
225
"""File system attributes."""
226
227
permission_key: str
228
"""Key of the permission set for the directory."""
229
230
file_id: str
231
"""Unique identifier for the directory."""
232
233
parent_id: str
234
"""Unique identifier of the parent directory."""
235
236
is_directory: bool
237
"""Whether this represents a directory (True for directories)."""
238
239
owner: Optional[str]
240
"""NFS only - The owner of the directory."""
241
242
group: Optional[str]
243
"""NFS only - The owning group of the directory."""
244
245
file_mode: Optional[str]
246
"""NFS only - The directory mode."""
247
248
nfs_file_type: Optional[Literal['Directory']]
249
"""NFS only - The type of the directory."""
250
```
251
252
## Handle and Lease Classes
253
254
### Handle
255
256
```python { .api }
257
from azure.storage.fileshare import Handle
258
from typing import List, Literal
259
260
class Handle:
261
"""A listed Azure Storage handle item."""
262
263
client_name: str
264
"""Name of the client machine where the share is being mounted."""
265
266
id: str
267
"""XSMB service handle ID."""
268
269
path: str
270
"""File or directory name including full path starting from share root."""
271
272
file_id: str
273
"""Unique identifier for the file or directory."""
274
275
parent_id: str
276
"""Unique identifier of the parent directory."""
277
278
session_id: str
279
"""SMB session ID in context of which the file handle was opened."""
280
281
client_ip: str
282
"""Client IP that opened the handle."""
283
284
open_time: datetime
285
"""Time when the handle was opened (UTC)."""
286
287
last_reconnect_time: Optional[datetime]
288
"""Time handle was last connected to (UTC)."""
289
290
access_rights: List[Literal['Read', 'Write', 'Delete']]
291
"""Access rights of the handle."""
292
```
293
294
### LeaseProperties
295
296
```python { .api }
297
from azure.storage.fileshare import LeaseProperties
298
299
class LeaseProperties:
300
"""Properties of a lease."""
301
302
status: str
303
"""The lease status (locked, unlocked)."""
304
305
state: str
306
"""Lease state (available, leased, expired, breaking, broken)."""
307
308
duration: str
309
"""Lease duration (infinite, fixed)."""
310
```
311
312
## Content and HTTP Settings
313
314
### ContentSettings
315
316
```python { .api }
317
from azure.storage.fileshare import ContentSettings
318
319
class ContentSettings:
320
"""HTTP content settings for a file."""
321
322
def __init__(
323
self,
324
content_type: Optional[str] = None,
325
content_encoding: Optional[str] = None,
326
content_language: Optional[str] = None,
327
content_disposition: Optional[str] = None,
328
cache_control: Optional[str] = None,
329
content_md5: Optional[bytearray] = None
330
) -> None:
331
"""
332
Initialize ContentSettings.
333
334
Parameters:
335
content_type: The content type (MIME type) of the file
336
content_encoding: Content encoding (e.g., 'gzip')
337
content_language: Content language (e.g., 'en-US')
338
content_disposition: Content disposition (e.g., 'attachment; filename=file.txt')
339
cache_control: Cache control directive (e.g., 'no-cache', 'max-age=3600')
340
content_md5: MD5 hash of the content for integrity verification
341
"""
342
343
content_type: str
344
"""The content type specified for the file. Default: 'application/octet-stream'."""
345
346
content_encoding: str
347
"""Content encoding value stored for the file."""
348
349
content_language: str
350
"""Content language value stored for the file."""
351
352
content_disposition: str
353
"""Content disposition value stored for the file."""
354
355
cache_control: str
356
"""Cache control value stored for the file."""
357
358
content_md5: bytearray
359
"""MD5 hash for message content integrity verification."""
360
```
361
362
### CopyProperties
363
364
```python { .api }
365
from azure.storage.fileshare import CopyProperties
366
367
class CopyProperties:
368
"""Properties of a copy operation."""
369
370
id: str
371
"""String identifier for the copy operation."""
372
373
source: str
374
"""URL of the source file (up to 2 KB)."""
375
376
status: str
377
"""State of the copy operation (pending, success, aborted, failed)."""
378
379
progress: str
380
"""Number of bytes copied and total bytes in source."""
381
382
completion_time: datetime
383
"""Completion time of the copy operation."""
384
385
status_description: str
386
"""Description of failed or pending copy operations."""
387
388
incremental_copy: bool
389
"""Whether this is an incremental copy operation."""
390
391
destination_snapshot: str
392
"""Destination snapshot for incremental copy operations."""
393
```
394
395
## Service Configuration Models
396
397
### Metrics
398
399
```python { .api }
400
from azure.storage.fileshare import Metrics, RetentionPolicy
401
402
class Metrics:
403
"""Request statistics grouped by API in hour or minute aggregates."""
404
405
def __init__(
406
self,
407
enabled: bool = False,
408
include_apis: bool = False,
409
retention_policy: Optional[RetentionPolicy] = None,
410
version: str = "1.0"
411
) -> None:
412
"""
413
Initialize Metrics.
414
415
Parameters:
416
enabled: Whether metrics are enabled for the File service
417
include_apis: Whether to generate summary statistics for API operations
418
retention_policy: How long the associated data should persist
419
version: Storage Analytics version (default: 1.0)
420
"""
421
422
version: str
423
"""The version of Storage Analytics to configure."""
424
425
enabled: bool
426
"""Whether metrics are enabled for the File service."""
427
428
include_apis: bool
429
"""Whether metrics should generate summary statistics for API operations."""
430
431
retention_policy: RetentionPolicy
432
"""Determines how long the associated data should persist."""
433
```
434
435
### RetentionPolicy
436
437
```python { .api }
438
from azure.storage.fileshare import RetentionPolicy
439
440
class RetentionPolicy:
441
"""Retention policy for metrics or logging data."""
442
443
def __init__(
444
self,
445
enabled: bool = False,
446
days: Optional[int] = None
447
) -> None:
448
"""
449
Initialize RetentionPolicy.
450
451
Parameters:
452
enabled: Whether a retention policy is enabled
453
days: Number of days data should be retained (1-365)
454
"""
455
456
enabled: bool
457
"""Whether a retention policy is enabled for the storage service."""
458
459
days: Optional[int]
460
"""Number of days that data should be retained (1-365 when enabled)."""
461
```
462
463
### CorsRule
464
465
```python { .api }
466
from azure.storage.fileshare import CorsRule
467
468
class CorsRule:
469
"""CORS rule for cross-origin resource sharing."""
470
471
def __init__(
472
self,
473
allowed_origins: Union[str, List[str]],
474
allowed_methods: Union[str, List[str]],
475
allowed_headers: Union[str, List[str]] = "",
476
exposed_headers: Union[str, List[str]] = "",
477
max_age_in_seconds: int = 0
478
) -> None:
479
"""
480
Initialize CorsRule.
481
482
Parameters:
483
allowed_origins: Origin domains allowed via CORS, or "*" for all
484
allowed_methods: HTTP methods allowed to be executed by the origin
485
allowed_headers: Headers allowed to be part of the cross-origin request
486
exposed_headers: Response headers to expose to CORS clients
487
max_age_in_seconds: Seconds client/browser should cache preflight response
488
"""
489
490
allowed_origins: str
491
"""Comma-delimited list of allowed origin domains or "*" for all."""
492
493
allowed_methods: str
494
"""Comma-delimited list of allowed HTTP methods."""
495
496
allowed_headers: str
497
"""Comma-delimited list of allowed request headers."""
498
499
exposed_headers: str
500
"""Comma-delimited list of response headers to expose."""
501
502
max_age_in_seconds: int
503
"""Seconds to cache preflight response."""
504
```
505
506
## Access Control Models
507
508
### AccessPolicy
509
510
```python { .api }
511
from azure.storage.fileshare import AccessPolicy, ShareSasPermissions
512
from datetime import datetime
513
514
class AccessPolicy:
515
"""Access policy for a share."""
516
517
def __init__(
518
self,
519
permission: Optional[Union[ShareSasPermissions, str]] = None,
520
expiry: Optional[datetime] = None,
521
start: Optional[datetime] = None
522
) -> None:
523
"""
524
Initialize AccessPolicy.
525
526
Parameters:
527
permission: Permissions associated with the shared access signature
528
expiry: Time at which the shared access signature becomes invalid
529
start: Time at which the shared access signature becomes valid
530
"""
531
532
permission: Union[ShareSasPermissions, str]
533
"""The permissions associated with the shared access signature."""
534
535
expiry: datetime
536
"""The time at which the shared access signature becomes invalid."""
537
538
start: datetime
539
"""The time at which the shared access signature becomes valid."""
540
```
541
542
### ShareSasPermissions
543
544
```python { .api }
545
from azure.storage.fileshare import ShareSasPermissions
546
547
class ShareSasPermissions:
548
"""ShareSasPermissions class for generating shared access signatures."""
549
550
def __init__(
551
self,
552
read: bool = False,
553
create: bool = False,
554
write: bool = False,
555
delete: bool = False,
556
list: bool = False
557
) -> None:
558
"""
559
Initialize ShareSasPermissions.
560
561
Parameters:
562
read: Read content, properties, metadata of any file in the share
563
create: Create a new file or copy a file to a new file in the share
564
write: Create or write content, properties, metadata. Resize files
565
delete: Delete any file in the share
566
list: List files and directories in the share
567
"""
568
569
read: bool
570
"""Read the content, properties, metadata of any file in the share."""
571
572
create: bool
573
"""Create a new file in the share, or copy a file to a new file."""
574
575
write: bool
576
"""Create or write content, properties, metadata. Resize the file."""
577
578
delete: bool
579
"""Delete any file in the share."""
580
581
list: bool
582
"""List files and directories in the share."""
583
584
@classmethod
585
def from_string(cls, permission: str) -> ShareSasPermissions:
586
"""
587
Create ShareSasPermissions from a string.
588
589
Parameters:
590
permission: Permission string (r=read, c=create, w=write, d=delete, l=list)
591
592
Returns:
593
ShareSasPermissions: Configured permissions object
594
"""
595
```
596
597
### FileSasPermissions
598
599
```python { .api }
600
from azure.storage.fileshare import FileSasPermissions
601
602
class FileSasPermissions:
603
"""FileSasPermissions class for generating shared access signatures."""
604
605
def __init__(
606
self,
607
read: bool = False,
608
create: bool = False,
609
write: bool = False,
610
delete: bool = False
611
) -> None:
612
"""
613
Initialize FileSasPermissions.
614
615
Parameters:
616
read: Read content, properties, metadata. Use as source of copy operation
617
create: Create a new file or copy a file to a new file
618
write: Create or write content, properties, metadata. Resize file
619
delete: Delete the file
620
"""
621
622
read: bool
623
"""Read the content, properties, metadata."""
624
625
create: bool
626
"""Create a new file or copy a file to a new file."""
627
628
write: bool
629
"""Create or write content, properties, metadata. Resize the file."""
630
631
delete: bool
632
"""Delete the file."""
633
634
@classmethod
635
def from_string(cls, permission: str) -> FileSasPermissions:
636
"""
637
Create FileSasPermissions from a string.
638
639
Parameters:
640
permission: Permission string (r=read, c=create, w=write, d=delete)
641
642
Returns:
643
FileSasPermissions: Configured permissions object
644
"""
645
```
646
647
## File System Attributes and Enums
648
649
### NTFSAttributes
650
651
```python { .api }
652
from azure.storage.fileshare import NTFSAttributes
653
654
class NTFSAttributes:
655
"""Valid set of attributes to set for file or directory.
656
657
To set attribute for directory, 'directory' should always be enabled
658
except setting 'none' for directory.
659
"""
660
661
read_only: bool = False
662
"""Enable/disable 'ReadOnly' attribute for DIRECTORY or FILE."""
663
664
hidden: bool = False
665
"""Enable/disable 'Hidden' attribute for DIRECTORY or FILE."""
666
667
system: bool = False
668
"""Enable/disable 'System' attribute for DIRECTORY or FILE."""
669
670
none: bool = False
671
"""Enable/disable 'None' attribute for DIRECTORY or FILE to clear all attributes of FILE/DIRECTORY."""
672
673
directory: bool = False
674
"""Enable/disable 'Directory' attribute for DIRECTORY."""
675
676
archive: bool = False
677
"""Enable/disable 'Archive' attribute for DIRECTORY."""
678
679
temporary: bool = False
680
"""Enable/disable 'Temporary' attribute for DIRECTORY."""
681
682
offline: bool = False
683
"""Enable/disable 'Offline' attribute for DIRECTORY."""
684
685
not_content_indexed: bool = False
686
"""Enable/disable 'NotContentIndexed' attribute for DIRECTORY."""
687
688
no_scrub_data: bool = False
689
"""Enable/disable 'NoScrubData' attribute for DIRECTORY."""
690
```
691
692
### ShareProtocols
693
694
```python { .api }
695
from azure.storage.fileshare import ShareProtocols
696
from enum import Enum
697
698
class ShareProtocols(str, Enum):
699
"""Enabled protocols on the share."""
700
701
SMB = "SMB"
702
"""Server Message Block protocol."""
703
704
NFS = "NFS"
705
"""Network File System protocol."""
706
```
707
708
### ShareRootSquash
709
710
```python { .api }
711
from azure.storage.fileshare import ShareRootSquash
712
from enum import Enum
713
714
class ShareRootSquash(str, Enum):
715
"""Root squash setting for NFS shares."""
716
717
NO_ROOT_SQUASH = "NoRootSquash"
718
"""No root squashing (default)."""
719
720
ROOT_SQUASH = "RootSquash"
721
"""Root user mapped to anonymous user."""
722
723
ALL_SQUASH = "AllSquash"
724
"""All users mapped to anonymous user."""
725
```
726
727
### ShareAccessTier
728
729
```python { .api }
730
from azure.storage.fileshare import ShareAccessTier
731
from enum import Enum
732
733
class ShareAccessTier(str, Enum):
734
"""Access tier for the share."""
735
736
COOL = "Cool"
737
"""Cool access tier for infrequently accessed data."""
738
739
HOT = "Hot"
740
"""Hot access tier for frequently accessed data."""
741
742
PREMIUM = "Premium"
743
"""Premium access tier for high-performance requirements."""
744
745
TRANSACTION_OPTIMIZED = "TransactionOptimized"
746
"""Transaction optimized tier for high transaction volumes."""
747
```
748
749
## Protocol Settings
750
751
### ShareProtocolSettings
752
753
```python { .api }
754
from azure.storage.fileshare import ShareProtocolSettings, ShareSmbSettings
755
756
class ShareProtocolSettings:
757
"""Protocol settings for share."""
758
759
def __init__(self, smb: Optional[ShareSmbSettings] = None) -> None:
760
"""
761
Initialize ShareProtocolSettings.
762
763
Parameters:
764
smb: SMB protocol settings
765
"""
766
767
smb: ShareSmbSettings
768
"""Settings for SMB protocol."""
769
```
770
771
### ShareSmbSettings
772
773
```python { .api }
774
from azure.storage.fileshare import ShareSmbSettings, SmbMultichannel
775
776
class ShareSmbSettings:
777
"""Settings for SMB protocol."""
778
779
def __init__(self, multichannel: Optional[SmbMultichannel] = None) -> None:
780
"""
781
Initialize ShareSmbSettings.
782
783
Parameters:
784
multichannel: SMB multichannel settings
785
"""
786
787
multichannel: SmbMultichannel
788
"""Settings for SMB multichannel."""
789
```
790
791
### SmbMultichannel
792
793
```python { .api }
794
from azure.storage.fileshare import SmbMultichannel
795
796
class SmbMultichannel:
797
"""Settings for SMB multichannel."""
798
799
def __init__(self, enabled: bool = False) -> None:
800
"""
801
Initialize SmbMultichannel.
802
803
Parameters:
804
enabled: Whether SMB multichannel is enabled
805
"""
806
807
enabled: bool
808
"""If SMB multichannel is enabled."""
809
```
810
811
## Usage Examples
812
813
### Working with File Properties
814
815
```python { .api }
816
from azure.storage.fileshare import ShareFileClient, ContentSettings, NTFSAttributes
817
from datetime import datetime, timezone
818
819
# Get comprehensive file properties
820
file_client = ShareFileClient.from_connection_string(
821
conn_str, "share", "myfile.txt"
822
)
823
824
properties = file_client.get_file_properties()
825
826
# Access all property types
827
print(f"File name: {properties.name}")
828
print(f"File size: {properties.size} bytes")
829
print(f"Content type: {properties.content_settings.content_type}")
830
print(f"Last modified: {properties.last_modified}")
831
print(f"ETag: {properties.etag}")
832
print(f"Server encrypted: {properties.server_encrypted}")
833
834
# File system attributes
835
print(f"File attributes: {properties.file_attributes}")
836
print(f"Creation time: {properties.creation_time}")
837
print(f"Last write time: {properties.last_write_time}")
838
print(f"File ID: {properties.file_id}")
839
840
# Metadata
841
for key, value in properties.metadata.items():
842
print(f"Metadata {key}: {value}")
843
844
# Copy properties (if file was copied)
845
if properties.copy.id:
846
print(f"Copy ID: {properties.copy.id}")
847
print(f"Copy status: {properties.copy.status}")
848
print(f"Copy progress: {properties.copy.progress}")
849
850
# Lease properties
851
print(f"Lease status: {properties.lease.status}")
852
print(f"Lease state: {properties.lease.state}")
853
```
854
855
### Configuring Content Settings
856
857
```python { .api }
858
from azure.storage.fileshare import ContentSettings
859
860
# Create comprehensive content settings
861
content_settings = ContentSettings(
862
content_type="application/json",
863
content_encoding="gzip",
864
content_language="en-US",
865
content_disposition="attachment; filename=data.json",
866
cache_control="max-age=3600, must-revalidate"
867
)
868
869
# Apply to file
870
file_client.set_http_headers(content_settings=content_settings)
871
872
# Create settings for different file types
873
pdf_settings = ContentSettings(
874
content_type="application/pdf",
875
content_disposition="inline; filename=document.pdf",
876
cache_control="public, max-age=86400"
877
)
878
879
image_settings = ContentSettings(
880
content_type="image/jpeg",
881
cache_control="public, max-age=31536000" # 1 year
882
)
883
884
text_settings = ContentSettings(
885
content_type="text/plain; charset=utf-8",
886
content_encoding="utf-8"
887
)
888
```
889
890
### Working with NTFS Attributes
891
892
```python { .api }
893
from azure.storage.fileshare import NTFSAttributes
894
895
# Set file attributes using bitwise operations
896
readonly_archived = NTFSAttributes.ReadOnly | NTFSAttributes.Archive
897
hidden_system = NTFSAttributes.Hidden | NTFSAttributes.System
898
normal_file = NTFSAttributes.Normal
899
900
# Set attributes on file
901
file_client.set_http_headers(file_attributes=readonly_archived)
902
903
# Set directory attributes (Directory flag is required)
904
directory_attrs = NTFSAttributes.Directory | NTFSAttributes.Archive
905
directory_client.set_http_headers(file_attributes=directory_attrs)
906
907
# Check specific attributes
908
props = file_client.get_file_properties()
909
current_attrs = props.file_attributes
910
911
if isinstance(current_attrs, int):
912
is_readonly = bool(current_attrs & NTFSAttributes.ReadOnly)
913
is_hidden = bool(current_attrs & NTFSAttributes.Hidden)
914
is_archive = bool(current_attrs & NTFSAttributes.Archive)
915
916
print(f"Read-only: {is_readonly}")
917
print(f"Hidden: {is_hidden}")
918
print(f"Archive: {is_archive}")
919
```
920
921
### Configuring Service Properties
922
923
```python { .api }
924
from azure.storage.fileshare import (
925
ShareServiceClient, Metrics, RetentionPolicy, CorsRule,
926
ShareProtocolSettings, ShareSmbSettings, SmbMultichannel
927
)
928
929
service_client = ShareServiceClient.from_connection_string(conn_str)
930
931
# Configure metrics
932
retention = RetentionPolicy(enabled=True, days=7)
933
hour_metrics = Metrics(
934
enabled=True,
935
include_apis=True,
936
retention_policy=retention,
937
version="1.0"
938
)
939
940
minute_metrics = Metrics(
941
enabled=True,
942
include_apis=False,
943
retention_policy=retention
944
)
945
946
# Configure CORS
947
cors_rules = [
948
CorsRule(
949
allowed_origins=["https://mywebsite.com", "https://www.mywebsite.com"],
950
allowed_methods=["GET", "PUT", "POST", "DELETE", "HEAD"],
951
allowed_headers=["x-ms-*", "content-type", "accept"],
952
exposed_headers=["x-ms-*"],
953
max_age_in_seconds=3600
954
),
955
CorsRule(
956
allowed_origins=["https://admin.mywebsite.com"],
957
allowed_methods=["GET", "PUT", "POST"],
958
allowed_headers=["*"],
959
exposed_headers=["*"],
960
max_age_in_seconds=7200
961
)
962
]
963
964
# Configure SMB protocol settings
965
smb_multichannel = SmbMultichannel(enabled=True)
966
smb_settings = ShareSmbSettings(multichannel=smb_multichannel)
967
protocol_settings = ShareProtocolSettings(smb=smb_settings)
968
969
# Apply all settings
970
service_client.set_service_properties(
971
hour_metrics=hour_metrics,
972
minute_metrics=minute_metrics,
973
cors=cors_rules,
974
protocol=protocol_settings
975
)
976
```
977
978
### Working with Permissions
979
980
```python { .api }
981
from azure.storage.fileshare import ShareSasPermissions, FileSasPermissions, AccessPolicy
982
from datetime import datetime, timedelta
983
984
# Create permission objects
985
share_permissions = ShareSasPermissions(
986
read=True,
987
write=True,
988
create=True,
989
list=True
990
)
991
992
file_permissions = FileSasPermissions(
993
read=True,
994
write=True
995
)
996
997
# Use with access policies
998
read_only_policy = AccessPolicy(
999
permission=ShareSasPermissions(read=True, list=True),
1000
expiry=datetime.utcnow() + timedelta(days=30),
1001
start=datetime.utcnow()
1002
)
1003
1004
write_policy = AccessPolicy(
1005
permission=ShareSasPermissions(read=True, write=True, create=True, delete=True),
1006
expiry=datetime.utcnow() + timedelta(hours=2),
1007
start=datetime.utcnow()
1008
)
1009
1010
# Set policies on share
1011
share_client.set_share_access_policy({
1012
"readonly": read_only_policy,
1013
"write": write_policy
1014
})
1015
1016
# Create permissions from strings
1017
share_perms_from_string = ShareSasPermissions.from_string("rwcl") # read, write, create, list
1018
file_perms_from_string = FileSasPermissions.from_string("rw") # read, write
1019
```
1020
1021
### Working with Share Properties
1022
1023
```python { .api }
1024
from azure.storage.fileshare import ShareClient, ShareProtocols, ShareRootSquash
1025
1026
share_client = ShareClient.from_connection_string(conn_str, "myshare")
1027
1028
# Get comprehensive share properties
1029
properties = share_client.get_share_properties()
1030
1031
print(f"Share name: {properties.name}")
1032
print(f"Quota: {properties.quota} GB")
1033
print(f"Last modified: {properties.last_modified}")
1034
print(f"Access tier: {properties.access_tier}")
1035
print(f"Protocols: {properties.protocols}")
1036
print(f"Root squash: {properties.root_squash}")
1037
1038
# Premium share properties
1039
if properties.provisioned_iops:
1040
print(f"Provisioned IOPS: {properties.provisioned_iops}")
1041
print(f"Provisioned bandwidth: {properties.provisioned_bandwidth} Mbps")
1042
print(f"Provisioned egress: {properties.provisioned_egress_mbps} Mbps")
1043
1044
# Soft-deleted share properties
1045
if properties.deleted:
1046
print(f"Deleted time: {properties.deleted_time}")
1047
print(f"Remaining retention days: {properties.remaining_retention_days}")
1048
1049
# Snapshot properties
1050
if properties.snapshot:
1051
print(f"Snapshot ID: {properties.snapshot}")
1052
1053
# Metadata
1054
for key, value in properties.metadata.items():
1055
print(f"Metadata {key}: {value}")
1056
1057
# Lease information
1058
lease = properties.lease
1059
print(f"Lease status: {lease.status}")
1060
print(f"Lease state: {lease.state}")
1061
print(f"Lease duration: {lease.duration}")
1062
```
1063
1064
### Handle Information
1065
1066
```python { .api }
1067
from azure.storage.fileshare import ShareDirectoryClient
1068
1069
directory_client = ShareDirectoryClient.from_connection_string(
1070
conn_str, "share", "directory"
1071
)
1072
1073
# List and examine handles
1074
handles = list(directory_client.list_handles(recursive=True))
1075
1076
for handle in handles:
1077
print(f"Handle ID: {handle.id}")
1078
print(f"Client: {handle.client_name} ({handle.client_ip})")
1079
print(f"Path: {handle.path}")
1080
print(f"File ID: {handle.file_id}")
1081
print(f"Session ID: {handle.session_id}")
1082
print(f"Opened: {handle.open_time}")
1083
1084
if handle.last_reconnect_time:
1085
print(f"Last reconnect: {handle.last_reconnect_time}")
1086
1087
print(f"Access rights: {', '.join(handle.access_rights)}")
1088
print("---")
1089
1090
# Close handles based on criteria
1091
for handle in handles:
1092
if 'Write' in handle.access_rights:
1093
result = directory_client.close_handle(handle)
1094
print(f"Closed write handle: {result['closed_handles_count']}")
1095
```
1096
1097
## Retry Policies
1098
1099
### ExponentialRetry
1100
1101
```python { .api }
1102
from azure.storage.fileshare import ExponentialRetry
1103
1104
class ExponentialRetry:
1105
"""Retry policy with exponential backoff."""
1106
1107
def __init__(
1108
self,
1109
initial_backoff: int = 15,
1110
max_backoff: int = 1000,
1111
retry_total: int = 3,
1112
random_jitter_range: int = 3,
1113
**kwargs: Any
1114
) -> None:
1115
"""
1116
Exponential retry policy implementation.
1117
1118
Parameters:
1119
initial_backoff: Initial backoff interval in seconds
1120
max_backoff: Maximum backoff interval in seconds
1121
retry_total: Total number of retry attempts
1122
random_jitter_range: Range for random jitter in seconds
1123
"""
1124
```
1125
1126
### LinearRetry
1127
1128
```python { .api }
1129
from azure.storage.fileshare import LinearRetry
1130
1131
class LinearRetry:
1132
"""Retry policy with linear backoff."""
1133
1134
def __init__(
1135
self,
1136
backoff: int = 15,
1137
retry_total: int = 3,
1138
random_jitter_range: int = 3,
1139
**kwargs: Any
1140
) -> None:
1141
"""
1142
Linear retry policy implementation.
1143
1144
Parameters:
1145
backoff: Fixed backoff interval in seconds
1146
retry_total: Total number of retry attempts
1147
random_jitter_range: Range for random jitter in seconds
1148
"""
1149
```
1150
1151
## Shared Access Signature Models
1152
1153
### LocationMode
1154
1155
```python { .api }
1156
from azure.storage.fileshare import LocationMode
1157
from enum import Enum
1158
1159
class LocationMode(str, Enum):
1160
"""Specifies the location mode for requests."""
1161
1162
PRIMARY = "primary"
1163
"""Requests are sent to the primary location."""
1164
1165
SECONDARY = "secondary"
1166
"""Requests are sent to the secondary location."""
1167
```
1168
1169
### ResourceTypes
1170
1171
```python { .api }
1172
from azure.storage.fileshare import ResourceTypes
1173
1174
class ResourceTypes:
1175
"""Valid resource types for account SAS."""
1176
1177
service: bool = False
1178
"""Permission to access service-level APIs."""
1179
1180
container: bool = False
1181
"""Permission to access container-level APIs."""
1182
1183
object: bool = False
1184
"""Permission to access object-level APIs."""
1185
1186
def __init__(
1187
self,
1188
service: bool = False,
1189
container: bool = False,
1190
object: bool = False
1191
) -> None:
1192
"""Initialize ResourceTypes with specified permissions."""
1193
```
1194
1195
### AccountSasPermissions
1196
1197
```python { .api }
1198
from azure.storage.fileshare import AccountSasPermissions
1199
1200
class AccountSasPermissions:
1201
"""Account SAS permissions."""
1202
1203
read: bool = False
1204
"""Permission to read resources and metadata."""
1205
1206
write: bool = False
1207
"""Permission to write resources."""
1208
1209
delete: bool = False
1210
"""Permission to delete resources."""
1211
1212
list: bool = False
1213
"""Permission to list resources."""
1214
1215
add: bool = False
1216
"""Permission to add resources."""
1217
1218
create: bool = False
1219
"""Permission to create resources."""
1220
1221
update: bool = False
1222
"""Permission to update resources."""
1223
1224
process: bool = False
1225
"""Permission to process queue messages."""
1226
1227
def __init__(
1228
self,
1229
read: bool = False,
1230
write: bool = False,
1231
delete: bool = False,
1232
list: bool = False,
1233
add: bool = False,
1234
create: bool = False,
1235
update: bool = False,
1236
process: bool = False
1237
) -> None:
1238
"""Initialize AccountSasPermissions with specified permissions."""
1239
```
1240
1241
### Services
1242
1243
```python { .api }
1244
from azure.storage.fileshare import Services
1245
1246
class Services:
1247
"""Valid services for account SAS."""
1248
1249
blob: bool = False
1250
"""Permission for Blob service."""
1251
1252
queue: bool = False
1253
"""Permission for Queue service."""
1254
1255
fileshare: bool = False
1256
"""Permission for File Share service."""
1257
1258
def __init__(
1259
self,
1260
blob: bool = False,
1261
queue: bool = False,
1262
fileshare: bool = False
1263
) -> None:
1264
"""Initialize Services with specified service permissions."""
1265
```
1266
1267
### StorageErrorCode
1268
1269
```python { .api }
1270
from azure.storage.fileshare import StorageErrorCode
1271
from enum import Enum
1272
1273
class StorageErrorCode(str, Enum):
1274
"""Common storage error codes."""
1275
1276
ACCOUNT_ALREADY_EXISTS = "AccountAlreadyExists"
1277
ACCOUNT_IS_DISABLED = "AccountIsDisabled"
1278
AUTHORIZATION_FAILURE = "AuthorizationFailure"
1279
CONDITION_NOT_MET = "ConditionNotMet"
1280
CONTAINER_NOT_FOUND = "ContainerNotFound"
1281
FEATURE_VERSION_MISMATCH = "FeatureVersionMismatch"
1282
INSUFFICIENT_ACCOUNT_PERMISSIONS = "InsufficientAccountPermissions"
1283
INTERNAL_ERROR = "InternalError"
1284
INVALID_AUTHENTICATION_INFO = "InvalidAuthenticationInfo"
1285
INVALID_HEADER_VALUE = "InvalidHeaderValue"
1286
INVALID_HTTP_VERB = "InvalidHttpVerb"
1287
INVALID_INPUT = "InvalidInput"
1288
INVALID_MD5 = "InvalidMd5"
1289
INVALID_METADATA = "InvalidMetadata"
1290
INVALID_QUERY_PARAMETER_VALUE = "InvalidQueryParameterValue"
1291
INVALID_RANGE = "InvalidRange"
1292
INVALID_RESOURCE_NAME = "InvalidResourceName"
1293
INVALID_URI = "InvalidUri"
1294
INVALID_XML_DOCUMENT = "InvalidXmlDocument"
1295
INVALID_XML_NODE_VALUE = "InvalidXmlNodeValue"
1296
MD5_MISMATCH = "Md5Mismatch"
1297
METADATA_TOO_LARGE = "MetadataTooLarge"
1298
MISSING_CONTENT_LENGTH_HEADER = "MissingContentLengthHeader"
1299
MISSING_REQUIRED_QUERY_PARAMETER = "MissingRequiredQueryParameter"
1300
MISSING_REQUIRED_HEADER = "MissingRequiredHeader"
1301
MISSING_REQUIRED_XML_NODE = "MissingRequiredXmlNode"
1302
MULTIPLE_CONDITION_HEADERS_NOT_SUPPORTED = "MultipleConditionHeadersNotSupported"
1303
OPERATION_TIMED_OUT = "OperationTimedOut"
1304
OUT_OF_RANGE_INPUT = "OutOfRangeInput"
1305
OUT_OF_RANGE_QUERY_PARAMETER_VALUE = "OutOfRangeQueryParameterValue"
1306
REQUEST_BODY_TOO_LARGE = "RequestBodyTooLarge"
1307
RESOURCE_ALREADY_EXISTS = "ResourceAlreadyExists"
1308
RESOURCE_NOT_FOUND = "ResourceNotFound"
1309
SERVER_BUSY = "ServerBusy"
1310
UNSUPPORTED_HEADER = "UnsupportedHeader"
1311
UNSUPPORTED_HTTP_VERB = "UnsupportedHttpVerb"
1312
UNSUPPORTED_QUERY_PARAMETER = "UnsupportedQueryParameter"
1313
UNSUPPORTED_XML_NODE = "UnsupportedXmlNode"
1314
```
1315
1316
The data models provide comprehensive access to all Azure File Share properties, enabling detailed inspection, configuration, and management of shares, files, directories, and related metadata through strongly-typed Python objects.