file_advanced_samples.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. #-------------------------------------------------------------------------
  2. # Microsoft Developer & Platform Evangelism
  3. #
  4. # Copyright (c) Microsoft Corporation. All rights reserved.
  5. #
  6. # THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
  7. # EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
  8. # OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
  9. #----------------------------------------------------------------------------------
  10. # The example companies, organizations, products, domain names,
  11. # e-mail addresses, logos, people, places, and events depicted
  12. # herein are fictitious. No association with any real company,
  13. # organization, product, domain name, email address, logo, person,
  14. # places, or events is intended or should be inferred.
  15. #--------------------------------------------------------------------------
  16. import os
  17. from random_data import RandomData
  18. from azure.storage.fileshare import ShareServiceClient
  19. from azure.storage.fileshare import CorsRule, RetentionPolicy, Metrics
  20. #
  21. # Azure File Service Sample - Demonstrate how to perform common tasks using the Microsoft Azure File Service.
  22. #
  23. # Documentation References:
  24. # - What is a Storage Account - http://azure.microsoft.com/en-us/documentation/articles/storage-whatis-account/
  25. # - Getting Started with Files - https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-file-storage/
  26. # - File Service Concepts - http://msdn.microsoft.com/en-us/library/dn166972.aspx
  27. # - File Service REST API - http://msdn.microsoft.com/en-us/library/dn167006.aspx
  28. # - Storage Emulator - http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/
  29. #
  30. class FileAdvancedSamples():
  31. def __init__(self):
  32. self.random_data = RandomData()
  33. # Runs all samples for Azure Storage File service.
  34. def run_all_samples(self, connection_string):
  35. print('Azure Storage File Advanced samples - Starting.')
  36. try:
  37. # Create an instance of ShareServiceClient
  38. service = ShareServiceClient.from_connection_string(conn_str=connection_string)
  39. # List shares
  40. print('\n\n* List shares *\n')
  41. self.list_shares(service)
  42. # Set Cors
  43. print('\n\n* Set cors rules *\n')
  44. self.set_cors_rules(service)
  45. # Set Service Properties
  46. print('\n\n* Set service properties *\n')
  47. self.set_service_properties(service)
  48. # Share, directory and file properties and metadata
  49. print('\n\n* Metadata and properties *\n')
  50. self.metadata_and_properties(service)
  51. except Exception as e:
  52. print('Error occurred in the sample.', e)
  53. finally:
  54. print('\nAzure Storage File Advanced samples - Completed.\n')
  55. # List file shares
  56. def list_shares(self, service):
  57. share_prefix = 'sharesample' + self.random_data.get_random_name(6)
  58. try:
  59. print('1. Create multiple shares with prefix: ', share_prefix)
  60. for i in range(5):
  61. service.create_share(share_name=share_prefix + str(i))
  62. print('2. List shares')
  63. shares = service.list_shares()
  64. for share in shares:
  65. print(' Share name:' + share.name)
  66. except Exception as e:
  67. print(e)
  68. finally:
  69. print('3. Delete shares with prefix:' + share_prefix)
  70. for i in range(5):
  71. service.delete_share(share_prefix + str(i))
  72. # Set CORS
  73. def set_cors_rules(self, service):
  74. print('1. Get Cors Rules')
  75. original_cors_rules = service.get_service_properties()['cors']
  76. print('2. Overwrite Cors Rules')
  77. cors_rule = CorsRule(
  78. allowed_origins=['*'],
  79. allowed_methods=['POST', 'GET'],
  80. allowed_headers=['*'],
  81. exposed_headers=['*'],
  82. max_age_in_seconds=3600)
  83. try:
  84. service.set_service_properties(cors=[cors_rule])
  85. except Exception as e:
  86. print(e)
  87. finally:
  88. #reverting cors rules back to the original ones
  89. print('3. Revert Cors Rules back the original ones')
  90. service.set_service_properties(cors=original_cors_rules)
  91. print("CORS sample completed")
  92. # Manage properties of the File service, including logging and metrics settings, and the default service version.
  93. def set_service_properties(self, service):
  94. print('1. Get File service properties')
  95. props = service.get_service_properties()
  96. retention = RetentionPolicy(enabled=True, days=5)
  97. hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=retention)
  98. minute_metrics = Metrics(enabled=False)
  99. try:
  100. print('2. Ovewrite File service properties')
  101. service.set_service_properties(hour_metrics=hour_metrics, minute_metrics=minute_metrics)
  102. finally:
  103. print('3. Revert File service properties back to the original ones')
  104. service.set_service_properties(hour_metrics=props['hour_metrics'], minute_metrics=props['minute_metrics'])
  105. print('4. Set File service properties completed')
  106. # Manage metadata and properties of the share
  107. def metadata_and_properties(self, service):
  108. share_name = 'sharename' + self.random_data.get_random_name(6)
  109. try:
  110. # All directories and share must be created in a parent share.
  111. # Max capacity: 5TB per share
  112. print('1. Create sample share with name ' + share_name)
  113. quota = 1 # in GB
  114. metadata = { "foo": "bar", "baz": "foo" }
  115. share_client = service.create_share(share_name=share_name)
  116. print('Sample share "'+ share_name +'" created.')
  117. print('2. Get share properties.')
  118. properties = share_client.get_share_properties()
  119. print('3. Get share metadata.')
  120. get_metadata = properties['metadata']
  121. for k, v in get_metadata.items():
  122. print("\t" + k + ": " + v)
  123. dir_name = 'dirname' + self.random_data.get_random_name(6)
  124. print('4. Create sample directory with name ' + dir_name)
  125. metadata = { "abc": "def", "jkl": "mno" }
  126. directory_client = share_client.create_directory(dir_name, metadata=metadata)
  127. print('Sample directory "'+ dir_name +'" created.')
  128. print('5. Get directory properties.')
  129. properties = directory_client.get_directory_properties()
  130. print('6. Get directory metadata.')
  131. get_metadata = properties['metadata']
  132. for k, v in get_metadata.items():
  133. print("\t" + k + ": " + v)
  134. file_name = 'sample.txt'
  135. # Uploading text to share_name/dir_name/sample.txt in Azure Files account.
  136. # Max capacity: 1TB per file
  137. print('7. Upload sample file from text to directory.')
  138. metadata = { "prop1": "val1", "prop2": "val2" }
  139. file_client = directory_client.get_file_client(file_name)
  140. file_client.upload_file('Hello World! - from text sample', metadata=metadata)
  141. print('Sample file "' + file_name + '" created and uploaded to: ' + share_name + '/' + dir_name)
  142. print('8. Get file properties.')
  143. properties = file_client.get_file_properties()
  144. print('9. Get file metadata.')
  145. get_metadata = properties['metadata']
  146. for k, v in get_metadata.items():
  147. print("\t" + k + ": " + v)
  148. # This is for demo purposes, all files will be deleted when share is deleted
  149. print('10. Delete file.')
  150. file_client.delete_file()
  151. # This is for demo purposes, all directories will be deleted when share is deleted
  152. print('11. Delete directory.')
  153. directory_client.delete_directory()
  154. finally:
  155. print('12. Delete share.')
  156. share_client.delete_share(share_name)
  157. print("Metadata and properties sample completed")