file_basic_samples.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. from random_data import RandomData
  17. import tempfile
  18. import os
  19. from azure.storage.fileshare import ShareServiceClient
  20. class FileBasicSamples():
  21. def __init__(self):
  22. self.random_data = RandomData()
  23. # Runs all samples for Azure Storage File service.
  24. def run_all_samples(self, connection_string):
  25. print('Azure Storage File Basis samples - Starting.')
  26. #declare variables
  27. filename = 'filesample' + self.random_data.get_random_name(6)
  28. sharename = 'sharesample' + self.random_data.get_random_name(6)
  29. try:
  30. # Create an instance of ShareServiceClient
  31. service = ShareServiceClient.from_connection_string(conn_str=connection_string)
  32. print('\n\n* Basic file operations *\n')
  33. self.basic_file_operations(sharename, filename, service)
  34. except Exception as e:
  35. print('error:' + e)
  36. finally:
  37. # Delete all Azure Files created in this sample
  38. self.file_delete_samples(sharename, filename, service)
  39. print('\nAzure Storage File Basic samples - Completed.\n')
  40. def basic_file_operations(self, sharename, filename, service):
  41. # Creating an SMB file share in your Azure Files account.
  42. print('\nAttempting to create a sample file from text for upload demonstration.')
  43. # All directories and share must be created in a parent share.
  44. # Max capacity: 5TB per share
  45. print('Creating sample share.')
  46. share_client = service.create_share(share_name=sharename)
  47. print('Sample share "'+ sharename +'" created.')
  48. # Creating an optional file directory in your Azure Files account.
  49. print('Creating a sample directory.')
  50. # Get the directory client
  51. directory_client = share_client.create_directory("mydirectory")
  52. print('Sample directory "mydirectory" created.')
  53. # Uploading text to sharename/mydirectory/my_text_file in Azure Files account.
  54. # Max capacity: 1TB per file
  55. print('Uploading a sample file from text.')
  56. # create_file_client
  57. file_client = directory_client.get_file_client(filename)
  58. # Upload a file
  59. file_client.upload_file('Hello World! - from text sample')
  60. print('Sample file "' + filename + '" created and uploaded to: ' + sharename + '/mydirectory')
  61. # Demonstrate how to copy a file
  62. print('\nCopying file ' + filename)
  63. # Create another file client which will copy the file from url
  64. destination_file_client = share_client.get_file_client('file1copy')
  65. # Copy the sample source file from the url to the destination file
  66. copy_resp = destination_file_client.start_copy_from_url(source_url=file_client.url)
  67. if copy_resp['copy_status'] == 'pending':
  68. # Demonstrate how to abort a copy operation (just for demo, probably will never get here)
  69. print('Abort copy operation')
  70. destination_file.abort_copy()
  71. else:
  72. print('Copy was a ' + copy_resp['copy_status'])
  73. # Demonstrate how to create a share and upload a file from a local temporary file path
  74. print('\nAttempting to upload a sample file from path for upload demonstration.')
  75. # Creating a temporary file to upload to Azure Files
  76. print('Creating a temporary file from text.')
  77. with tempfile.NamedTemporaryFile(delete=False) as my_temp_file:
  78. my_temp_file.file.write(b"Hello world!")
  79. print('Sample temporary file created.')
  80. # Uploading my_temp_file to sharename folder in Azure Files
  81. # Max capacity: 1TB per file
  82. print('Uploading a sample file from local path.')
  83. # Create file_client
  84. file_client = share_client.get_file_client(filename)
  85. # Upload a file
  86. with open(my_temp_file.name, "rb") as source_file:
  87. file_client.upload_file(source_file)
  88. print('Sample file "' + filename + '" uploaded from path to share: ' + sharename)
  89. # Close the temp file
  90. my_temp_file.close()
  91. # Get the list of valid ranges and write to the specified range
  92. print('\nGet list of valid ranges of the file.')
  93. file_ranges = file_client.get_ranges()
  94. data = b'abcdefghijkl'
  95. print('Put a range of data to the file.')
  96. file_client.upload_range(data=data, offset=file_ranges[0]['start'], length=len(data))
  97. # Demonstrate how to download a file from Azure Files
  98. # The following example download the file that was previously uploaded to Azure Files
  99. print('\nAttempting to download a sample file from Azure files for demonstration.')
  100. destination_file = tempfile.tempdir + '\mypathfile.txt'
  101. with open(destination_file, "wb") as file_handle:
  102. data = file_client.download_file()
  103. data.readinto(file_handle)
  104. print('Sample file downloaded to: ' + destination_file)
  105. # Demonstrate how to list files and directories contains under Azure File share
  106. print('\nAttempting to list files and directories directory under share "' + sharename + '":')
  107. # Create a generator to list directories and files under share
  108. # This is not a recursive listing operation
  109. generator = share_client.list_directories_and_files()
  110. # Prints the directories and files under the share
  111. for file_or_dir in generator:
  112. print(file_or_dir['name'])
  113. # remove temp file
  114. os.remove(my_temp_file.name)
  115. print('Files and directories under share "' + sharename + '" listed.')
  116. print('\nCompleted successfully - Azure basic Files operations.')
  117. # Demonstrate how to delete azure files created for this demonstration
  118. # Warning: Deleting a share or directory will also delete all files and directories that are contained in it.
  119. def file_delete_samples(self, sharename, filename, service):
  120. print('\nDeleting all samples created for this demonstration.')
  121. try:
  122. # Deleting file: 'sharename/mydirectory/filename'
  123. # This is for demo purposes only, it's unnecessary, as we're deleting the share later
  124. print('Deleting a sample file.')
  125. share_client = service.get_share_client(sharename)
  126. directory_client = share_client.get_directory_client('mydirectory')
  127. directory_client.delete_file(file_name=filename)
  128. print('Sample file "' + filename + '" deleted from: ' + sharename + '/mydirectory' )
  129. # Deleting directory: 'sharename/mydirectory'
  130. print('Deleting sample directory and all files and directories under it.')
  131. share_client.delete_directory('mydirectory')
  132. print('Sample directory "/mydirectory" deleted from: ' + sharename)
  133. # Deleting share: 'sharename'
  134. print('Deleting sample share ' + sharename + ' and all files and directories under it.')
  135. share_client.delete_share(sharename)
  136. print('Sample share "' + sharename + '" deleted.')
  137. print('\nCompleted successfully - Azure Files samples deleted.')
  138. except Exception as e:
  139. print('********ErrorDelete***********')
  140. print(e)