table_advanced_samples_7.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. def table_operations_with_sas(self, account):
  2. table_name = 'sastable' + self.random_data.get_random_name(6)
  3. try:
  4. # Create a Table Service object
  5. table_service = account.create_table_service()
  6. print('1. Create table with name - ' + table_name)
  7. table_service.create_table(table_name)
  8. # Create a Shared Access Signature for the table
  9. print('2. Get sas for table')
  10. table_sas = table_service.generate_table_shared_access_signature(
  11. table_name,
  12. TablePermissions.QUERY + TablePermissions.ADD + TablePermissions.UPDATE + TablePermissions.DELETE,
  13. datetime.datetime.utcnow() + datetime.timedelta(hours=1))
  14. shared_account = TableStorageAccount(account_name=account.account_name, sas_token=table_sas, endpoint_suffix=account.endpoint_suffix)
  15. shared_table_service = shared_account.create_table_service()
  16. # Create a sample entity to insert into the table
  17. customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '555-555-5555'}
  18. # Insert the entity into the table
  19. print('3. Insert new entity into table with sas - ' + table_name)
  20. shared_table_service.insert_entity(table_name, customer)
  21. # Demonstrate how to query the entity
  22. print('4. Read the inserted entity with sas.')
  23. entity = shared_table_service.get_entity(table_name, 'Harp', '1')
  24. print(entity['email'])
  25. print(entity['phone'])
  26. # Demonstrate how to update the entity by changing the phone number
  27. print('5. Update an existing entity by changing the phone number with sas')
  28. customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '425-123-1234'}
  29. shared_table_service.update_entity(table_name, customer)
  30. # Demonstrate how to delete an entity
  31. print('6. Delete the entity with sas')
  32. shared_table_service.delete_entity(table_name, 'Harp', '1')
  33. finally:
  34. print('7. Delete table')
  35. if(table_service.exists(table_name)):
  36. table_service.delete_table(table_name)
  37. print("Table operations with sas completed")