table-storage.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 config
  17. import datetime
  18. import time
  19. from random_data import RandomData
  20. from tablestorageaccount import TableStorageAccount
  21. from azure.storage import CloudStorageAccount, AccessPolicy
  22. from azure.storage.table import TableService, Entity, TablePermissions
  23. from azure.storage.models import CorsRule, Logging, Metrics, RetentionPolicy, ResourceTypes, AccountPermissions
  24. #
  25. # Azure Table Service Sample - Demonstrate how to perform common tasks using the Microsoft Azure Table Service
  26. # including creating a table, CRUD operations and different querying techniques.
  27. #
  28. # Documentation References:
  29. # - What is a Storage Account - http://azure.microsoft.com/en-us/documentation/articles/storage-whatis-account/
  30. # - Getting Started with Tables - https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-table-storage/
  31. # - Table Service Concepts - http://msdn.microsoft.com/en-us/library/dd179463.aspx
  32. # - Table Service REST API - http://msdn.microsoft.com/en-us/library/dd179423.aspx
  33. # - Table Service Python API - http://azure.github.io/azure-storage-python/ref/azure.storage.table.html
  34. # - Storage Emulator - http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/
  35. #
  36. class TableAdvancedSamples():
  37. def __init__(self):
  38. self.random_data = RandomData()
  39. # Runs all samples for Azure Storage Table service.
  40. def run_all_samples(self, account):
  41. table_service = account.create_table_service()
  42. print('Azure Storage Advanced Table samples - Starting.')
  43. print('\n\n* List tables *\n')
  44. self.list_tables(table_service)
  45. if not account.is_azure_cosmosdb_table():
  46. print('\n\n* Set service properties *\n')
  47. self.set_service_properties(table_service)
  48. print('\n\n* Set Cors rules *\n')
  49. self.set_cors_rules(table_service)
  50. print('\n\n* ACL operations *\n')
  51. self.table_acl_operations(table_service)
  52. if (config.IS_EMULATED):
  53. print('\n\n* Shared Access Signature is not supported in emulator *\n')
  54. else:
  55. print('\n\n* SAS operations *\n')
  56. self.table_operations_with_sas(account)
  57. print('\nAzure Storage Advanced Table samples - Completed.\n')
  58. # Manage tables including creating, listing and deleting
  59. def list_tables(self, table_service):
  60. table_prefix = 'table' + self.random_data.get_random_name(6)
  61. try:
  62. # Create tables
  63. for i in range(5):
  64. table_name = table_prefix + str(i)
  65. print('1. Create a table with name - ' + table_name)
  66. table_service.create_table(table_name)
  67. # List all the tables
  68. print('2. List tables')
  69. tables = table_service.list_tables()
  70. for table in tables:
  71. print('\Table Name: ' + table.name)
  72. finally:
  73. # Delete the tables
  74. print("3. Delete Tables")
  75. for i in range(5):
  76. table_name = table_prefix + str(i)
  77. if(table_service.exists(table_name)):
  78. table_service.delete_table(table_name)
  79. print("List tables sample completed")
  80. # Manage properties of the Table service, including logging and metrics settings, and the default service version.
  81. def set_service_properties(self, table_service):
  82. print('1. Get Table service properties')
  83. props = table_service.get_table_service_properties()
  84. retention = RetentionPolicy(enabled=True, days=5)
  85. logging = Logging(delete=True, read=False, write=True, retention_policy=retention)
  86. hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=retention)
  87. minute_metrics = Metrics(enabled=False)
  88. try:
  89. print('2. Ovewrite Table service properties')
  90. table_service.set_table_service_properties(logging=logging, hour_metrics=hour_metrics, minute_metrics=minute_metrics)
  91. finally:
  92. print('3. Revert Table service properties back to the original ones')
  93. table_service.set_table_service_properties(logging=props.logging, hour_metrics=props.hour_metrics, minute_metrics=props.minute_metrics)
  94. print('4. Set Table service properties completed')
  95. # Manage CORS rules on the table service
  96. def set_cors_rules(self, table_service):
  97. cors_rule = CorsRule(
  98. allowed_origins=['*'],
  99. allowed_methods=['POST', 'GET'],
  100. allowed_headers=['*'],
  101. exposed_headers=['*'],
  102. max_age_in_seconds=3600)
  103. print('1. Get Cors Rules')
  104. original_cors_rules = table_service.get_table_service_properties().cors
  105. try:
  106. print('2. Overwrite Cors Rules')
  107. table_service.set_table_service_properties(cors=[cors_rule])
  108. finally:
  109. #reverting cors rules back to the original ones
  110. print('3. Revert Cors Rules back the original ones')
  111. table_service.set_table_service_properties(cors=original_cors_rules)
  112. print("CORS sample completed")
  113. # Manage table access policy
  114. def table_acl_operations(self, table_service):
  115. table_name = 'acltable' + self.random_data.get_random_name(6)
  116. try:
  117. print('1. Create a table with name - ' + table_name)
  118. table_service.create_table(table_name)
  119. print('2. Set access policy for table')
  120. access_policy = AccessPolicy(permission=TablePermissions.QUERY,
  121. expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=1))
  122. identifiers = {'id': access_policy}
  123. table_service.set_table_acl(table_name, identifiers)
  124. print('3. Wait 30 seconds for acl to propagate')
  125. time.sleep(30)
  126. print('4. Get access policy from table')
  127. acl = table_service.get_table_acl(table_name)
  128. print('5. Clear access policy in table')
  129. table_service.set_table_acl(table_name)
  130. finally:
  131. print('5. Delete table')
  132. if(table_service.exists(table_name)):
  133. table_service.delete_table(table_name)
  134. print("Table ACL operations sample completed")
  135. # Manage shared access signature on a table
  136. def table_operations_with_sas(self, account):
  137. table_name = 'sastable' + self.random_data.get_random_name(6)
  138. try:
  139. # Create a Table Service object
  140. table_service = account.create_table_service()
  141. print('1. Create table with name - ' + table_name)
  142. table_service.create_table(table_name)
  143. # Create a Shared Access Signature for the table
  144. print('2. Get sas for table')
  145. table_sas = table_service.generate_table_shared_access_signature(
  146. table_name,
  147. TablePermissions.QUERY + TablePermissions.ADD + TablePermissions.UPDATE + TablePermissions.DELETE,
  148. datetime.datetime.utcnow() + datetime.timedelta(hours=1))
  149. shared_account = TableStorageAccount(account_name=account.account_name, sas_token=table_sas, endpoint_suffix=account.endpoint_suffix)
  150. shared_table_service = shared_account.create_table_service()
  151. # Create a sample entity to insert into the table
  152. customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '555-555-5555'}
  153. # Insert the entity into the table
  154. print('3. Insert new entity into table with sas - ' + table_name)
  155. shared_table_service.insert_entity(table_name, customer)
  156. # Demonstrate how to query the entity
  157. print('4. Read the inserted entity with sas.')
  158. entity = shared_table_service.get_entity(table_name, 'Harp', '1')
  159. print(entity['email'])
  160. print(entity['phone'])
  161. # Demonstrate how to update the entity by changing the phone number
  162. print('5. Update an existing entity by changing the phone number with sas')
  163. customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '425-123-1234'}
  164. shared_table_service.update_entity(table_name, customer)
  165. # Demonstrate how to delete an entity
  166. print('6. Delete the entity with sas')
  167. shared_table_service.delete_entity(table_name, 'Harp', '1')
  168. finally:
  169. print('7. Delete table')
  170. if(table_service.exists(table_name)):
  171. table_service.delete_table(table_name)
  172. print("Table operations with sas completed")