├── .gitignore ├── CONTRIBUTING.md ├── HelloWorld.png ├── LICENSE ├── README.md ├── config.py ├── random_data.py ├── requirements.txt ├── start.py ├── table_advanced_samples.py ├── table_basic_samples.py └── tablestorageaccount.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | Include/ 3 | Lib/ 4 | Scripts/ 5 | **.pyc 6 | tcl/ -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Azure samples 2 | 3 | Thank you for your interest in contributing to Azure samples! 4 | 5 | ## Ways to contribute 6 | 7 | You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways: 8 | 9 | - Submit feedback on [this sample page](https://azure.microsoft.com/documentation/samples/storage-table-python-getting-started/) whether it was helpful or not. 10 | - Submit issues through [issue tracker](https://github.com/Azure-Samples/storage-table-python-getting-started/issues) on GitHub. We are actively monitoring the issues and improving our samples. 11 | - If you wish to make code changes to samples, or contribute something new, please follow the [GitHub Forks / Pull requests model](https://help.github.com/articles/fork-a-repo/): Fork the sample repo, make the change and propose it back by submitting a pull request. -------------------------------------------------------------------------------- /HelloWorld.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Azure-Samples/storage-table-python-getting-started/f8e493eba97a601495a5f20d07e716cd6225502d/HelloWorld.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | services: storage 3 | platforms: python 4 | author: dineshmurthy 5 | --- 6 | 7 | # Azure Storage: Getting Started with Azure Storage in Python 8 | This demo demonstrates how to perform common tasks using Azure Table storage 9 | and Azure Cosmos DB Table API including creating a table, CRUD operations, 10 | batch operations and different querying techniques. 11 | 12 | If you don't have a Microsoft Azure subscription you can get a FREE trial 13 | account [here](http://go.microsoft.com/fwlink/?LinkId=330212) 14 | 15 | ##Minimum Requirements & Install Instructions 16 | Python 2.7, 3.3, or 3.4. 17 | To install Python, please go to https://www.python.org/downloads/ 18 | 19 | Please run 'pip install -r requirements.txt' to set up the Python environment. 20 | 21 | ## Running this sample 22 | 23 | ### Azure Cosmos DB Table API 24 | 25 | 1. Go to your Azure Cosmos DB Table API instance in the Azure Portal and select 26 | "Connection String" in the menu, select the Read-write Keys tab and copy the value 27 | in the "CONNECTION STRING" field. 28 | 2. Open config.py and set IS\_EMULATED to False and set STORAGE\_CONNECTION\_STRING to the 29 | connection string value from the previous step. 30 | 3. Run 'python start.py' 31 | 32 | #### More Information 33 | -[Introduction to Azure Cosmos DB Table API](https://docs.microsoft.com/en-us/azure/cosmos-db/table-introduction) 34 | 35 | ### Azure Table Storage 36 | 37 | This sample can be run using either the Azure Storage Emulator or with your 38 | Azure Storage account by updating the config.properties file with your 39 | connection string. 40 | 41 | To run the sample using the Storage Emulator (Only available on Microsoft 42 | Windows OS): 43 | 44 | 1. Download and install the Azure Storage Emulator https://azure.microsoft.com/en-us/downloads/ 45 | 2. Start the Azure Storage Emulator by pressing the Start button or the Windows 46 | key and searching for it by typing "Azure Storage Emulator". Select it from the 47 | list of applications to start it. 48 | 3. Open the config.py file and set IS\_EMULATED to true. 49 | 4. Run 'python start.py' 50 | 51 | To run the sample using the Storage Service: 52 | 53 | 1. Go to your Azure Storage account in the Azure Portal and under "SETTINGS" 54 | click on "Access keys". Copy either key1 or key2's "CONNECTION STRING". 55 | 2. Open config.py and set IS\_EMULATED to False and set STORAGE\_CONNECTION\_STRING to the 56 | connection string value from the previous step. 57 | 3. Run 'python start.py' 58 | 59 | #### More information 60 | - What is a Storage Account - http://azure.microsoft.com/en-us/documentation/articles/storage-whatis-account/ 61 | - Getting Started with Tables - https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-table-storage/ 62 | - Table Service Concepts - http://msdn.microsoft.com/en-us/library/dd179463.aspx 63 | - Table Service REST API - http://msdn.microsoft.com/en-us/library/dd179423.aspx 64 | - Storage Emulator - http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/ -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 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 | # Please do not include this file if you plan to contribute to this repo to assure your storage account name and key are not inadvertantly shared 17 | #-------------------------------------------------------------------------- 18 | 19 | IS_EMULATED = False 20 | STORAGE_CONNECTION_STRING = '' -------------------------------------------------------------------------------- /random_data.py: -------------------------------------------------------------------------------- 1 | import random, string 2 | from random import randint 3 | 4 | # Gets random data to use in samples 5 | class RandomData: 6 | # Gets random characters to use for generating unique name. 7 | def get_random_name(self, length): 8 | return ''.join(random.choice(string.ascii_lowercase) for i in range(length)) 9 | 10 | # Gets Random Bytes of specified size for use in samples. 11 | # Input Arguments: 12 | # size - size of random bytes to get 13 | def get_random_bytes(self, size): 14 | rand = random.Random() 15 | result = bytearray(size) 16 | for i in range(size): 17 | result[i] = rand.randint(0, 255) 18 | return bytes(result) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | azure-storage >= 0.34.3 -------------------------------------------------------------------------------- /start.py: -------------------------------------------------------------------------------- 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 | 17 | import config 18 | import azure.common 19 | from azure.storage import CloudStorageAccount 20 | from table_basic_samples import TableBasicSamples 21 | from table_advanced_samples import TableAdvancedSamples 22 | from tablestorageaccount import TableStorageAccount 23 | 24 | print('Azure Table Storage samples for Python') 25 | 26 | # Create the storage account object and specify its credentials 27 | # to either point to the local Emulator or your Azure subscription 28 | if config.IS_EMULATED: 29 | account = TableStorageAccount(is_emulated=True) 30 | else: 31 | account_connection_string = config.STORAGE_CONNECTION_STRING 32 | # Split into key=value pairs removing empties, then split the pairs into a dict 33 | config = dict(s.split('=', 1) for s in account_connection_string.split(';') if s) 34 | 35 | # Authentication 36 | account_name = config.get('AccountName') 37 | account_key = config.get('AccountKey') 38 | # Basic URL Configuration 39 | endpoint_suffix = config.get('EndpointSuffix') 40 | if endpoint_suffix == None: 41 | table_endpoint = config.get('TableEndpoint') 42 | table_prefix = '.table.' 43 | start_index = table_endpoint.find(table_prefix) 44 | end_index = table_endpoint.endswith(':') and len(table_endpoint) or table_endpoint.rfind(':') 45 | endpoint_suffix = table_endpoint[start_index+len(table_prefix):end_index] 46 | account = TableStorageAccount(account_name = account_name, connection_string = account_connection_string, endpoint_suffix=endpoint_suffix) 47 | #Basic Table samples 48 | print ('---------------------------------------------------------------') 49 | print('Azure Storage Table samples') 50 | table_basic_samples = TableBasicSamples() 51 | table_basic_samples.run_all_samples(account) 52 | 53 | #Advanced Table samples 54 | print ('---------------------------------------------------------------') 55 | print('Azure Storage Advanced Table samples') 56 | table_advanced_samples = TableAdvancedSamples() 57 | table_advanced_samples.run_all_samples(account) -------------------------------------------------------------------------------- /table_advanced_samples.py: -------------------------------------------------------------------------------- 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 | # 26 | # Azure Table Service Sample - Demonstrate how to perform common tasks using the Microsoft Azure Table Service 27 | # including creating a table, CRUD operations and different querying techniques. 28 | # 29 | # Documentation References: 30 | # - What is a Storage Account - http://azure.microsoft.com/en-us/documentation/articles/storage-whatis-account/ 31 | # - Getting Started with Tables - https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-table-storage/ 32 | # - Table Service Concepts - http://msdn.microsoft.com/en-us/library/dd179463.aspx 33 | # - Table Service REST API - http://msdn.microsoft.com/en-us/library/dd179423.aspx 34 | # - Table Service Python API - http://azure.github.io/azure-storage-python/ref/azure.storage.table.html 35 | # - Storage Emulator - http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/ 36 | # 37 | class TableAdvancedSamples(): 38 | 39 | def __init__(self): 40 | self.random_data = RandomData() 41 | 42 | # Runs all samples for Azure Storage Table service. 43 | def run_all_samples(self, account): 44 | table_service = account.create_table_service() 45 | print('Azure Storage Advanced Table samples - Starting.') 46 | 47 | print('\n\n* List tables *\n') 48 | self.list_tables(table_service) 49 | 50 | if not account.is_azure_cosmosdb_table(): 51 | print('\n\n* Set service properties *\n') 52 | self.set_service_properties(table_service) 53 | 54 | print('\n\n* Set Cors rules *\n') 55 | self.set_cors_rules(table_service) 56 | 57 | print('\n\n* ACL operations *\n') 58 | self.table_acl_operations(table_service) 59 | 60 | if (config.IS_EMULATED): 61 | print('\n\n* Shared Access Signature is not supported in emulator *\n') 62 | else: 63 | print('\n\n* SAS operations *\n') 64 | self.table_operations_with_sas(account) 65 | 66 | print('\nAzure Storage Advanced Table samples - Completed.\n') 67 | 68 | # Manage tables including creating, listing and deleting 69 | def list_tables(self, table_service): 70 | table_prefix = 'table' + self.random_data.get_random_name(6) 71 | 72 | try: 73 | # Create tables 74 | for i in range(5): 75 | table_name = table_prefix + str(i) 76 | print('1. Create a table with name - ' + table_name) 77 | table_service.create_table(table_name) 78 | 79 | # List all the tables 80 | print('2. List tables') 81 | tables = table_service.list_tables() 82 | for table in tables: 83 | print('\Table Name: ' + table.name) 84 | 85 | finally: 86 | # Delete the tables 87 | print("3. Delete Tables") 88 | for i in range(5): 89 | table_name = table_prefix + str(i) 90 | if(table_service.exists(table_name)): 91 | table_service.delete_table(table_name) 92 | 93 | print("List tables sample completed") 94 | 95 | # Manage properties of the Table service, including logging and metrics settings, and the default service version. 96 | def set_service_properties(self, table_service): 97 | print('1. Get Table service properties') 98 | props = table_service.get_table_service_properties() 99 | 100 | retention = RetentionPolicy(enabled=True, days=5) 101 | logging = Logging(delete=True, read=False, write=True, retention_policy=retention) 102 | hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=retention) 103 | minute_metrics = Metrics(enabled=False) 104 | 105 | try: 106 | print('2. Ovewrite Table service properties') 107 | table_service.set_table_service_properties(logging=logging, hour_metrics=hour_metrics, minute_metrics=minute_metrics) 108 | 109 | finally: 110 | print('3. Revert Table service properties back to the original ones') 111 | table_service.set_table_service_properties(logging=props.logging, hour_metrics=props.hour_metrics, minute_metrics=props.minute_metrics) 112 | 113 | print('4. Set Table service properties completed') 114 | 115 | # Manage CORS rules on the table service 116 | def set_cors_rules(self, table_service): 117 | cors_rule = CorsRule( 118 | allowed_origins=['*'], 119 | allowed_methods=['POST', 'GET'], 120 | allowed_headers=['*'], 121 | exposed_headers=['*'], 122 | max_age_in_seconds=3600) 123 | 124 | print('1. Get Cors Rules') 125 | original_cors_rules = table_service.get_table_service_properties().cors 126 | 127 | try: 128 | print('2. Overwrite Cors Rules') 129 | table_service.set_table_service_properties(cors=[cors_rule]) 130 | 131 | finally: 132 | #reverting cors rules back to the original ones 133 | print('3. Revert Cors Rules back the original ones') 134 | table_service.set_table_service_properties(cors=original_cors_rules) 135 | 136 | print("CORS sample completed") 137 | 138 | # Manage table access policy 139 | def table_acl_operations(self, table_service): 140 | table_name = 'acltable' + self.random_data.get_random_name(6) 141 | 142 | try: 143 | print('1. Create a table with name - ' + table_name) 144 | table_service.create_table(table_name) 145 | 146 | print('2. Set access policy for table') 147 | access_policy = AccessPolicy(permission=TablePermissions.QUERY, 148 | expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=1)) 149 | identifiers = {'id': access_policy} 150 | table_service.set_table_acl(table_name, identifiers) 151 | 152 | print('3. Wait 30 seconds for acl to propagate') 153 | time.sleep(30) 154 | 155 | print('4. Get access policy from table') 156 | acl = table_service.get_table_acl(table_name) 157 | 158 | print('5. Clear access policy in table') 159 | table_service.set_table_acl(table_name) 160 | 161 | finally: 162 | print('5. Delete table') 163 | if(table_service.exists(table_name)): 164 | table_service.delete_table(table_name) 165 | 166 | print("Table ACL operations sample completed") 167 | 168 | # Manage shared access signature on a table 169 | def table_operations_with_sas(self, account): 170 | table_name = 'sastable' + self.random_data.get_random_name(6) 171 | 172 | try: 173 | # Create a Table Service object 174 | table_service = account.create_table_service() 175 | 176 | print('1. Create table with name - ' + table_name) 177 | table_service.create_table(table_name) 178 | 179 | # Create a Shared Access Signature for the table 180 | print('2. Get sas for table') 181 | 182 | table_sas = table_service.generate_table_shared_access_signature( 183 | table_name, 184 | TablePermissions.QUERY + TablePermissions.ADD + TablePermissions.UPDATE + TablePermissions.DELETE, 185 | datetime.datetime.utcnow() + datetime.timedelta(hours=1)) 186 | 187 | shared_account = TableStorageAccount(account_name=account.account_name, sas_token=table_sas, endpoint_suffix=account.endpoint_suffix) 188 | shared_table_service = shared_account.create_table_service() 189 | 190 | # Create a sample entity to insert into the table 191 | customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '555-555-5555'} 192 | 193 | # Insert the entity into the table 194 | print('3. Insert new entity into table with sas - ' + table_name) 195 | shared_table_service.insert_entity(table_name, customer) 196 | 197 | # Demonstrate how to query the entity 198 | print('4. Read the inserted entity with sas.') 199 | entity = shared_table_service.get_entity(table_name, 'Harp', '1') 200 | 201 | print(entity['email']) 202 | print(entity['phone']) 203 | 204 | # Demonstrate how to update the entity by changing the phone number 205 | print('5. Update an existing entity by changing the phone number with sas') 206 | customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '425-123-1234'} 207 | shared_table_service.update_entity(table_name, customer) 208 | 209 | # Demonstrate how to delete an entity 210 | print('6. Delete the entity with sas') 211 | shared_table_service.delete_entity(table_name, 'Harp', '1') 212 | 213 | finally: 214 | print('7. Delete table') 215 | if(table_service.exists(table_name)): 216 | table_service.delete_table(table_name) 217 | 218 | print("Table operations with sas completed") -------------------------------------------------------------------------------- /table_basic_samples.py: -------------------------------------------------------------------------------- 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 | from random_data import RandomData 18 | from azure.storage import CloudStorageAccount 19 | from azure.storage.table import TableService, Entity 20 | 21 | # 22 | # Azure Table Service Sample - Demonstrate how to perform common tasks using the Microsoft Azure Table Service 23 | # including creating a table, CRUD operations and different querying techniques. 24 | # 25 | # Documentation References: 26 | # - What is a Storage Account - http://azure.microsoft.com/en-us/documentation/articles/storage-whatis-account/ 27 | # - Getting Started with Tables - https://azure.microsoft.com/en-us/documentation/articles/storage-python-how-to-use-table-storage/ 28 | # - Table Service Concepts - http://msdn.microsoft.com/en-us/library/dd179463.aspx 29 | # - Table Service REST API - http://msdn.microsoft.com/en-us/library/dd179423.aspx 30 | # - Table Service Python API - http://azure.github.io/azure-storage-ruby/ 31 | # - Storage Emulator - http://azure.microsoft.com/en-us/documentation/articles/storage-use-emulator/ 32 | # 33 | class TableBasicSamples(): 34 | 35 | def __init__(self): 36 | self.random_data = RandomData() 37 | 38 | # Runs all samples for Azure Storage Table service. 39 | def run_all_samples(self, account): 40 | print('Azure Storage Basic Table samples - Starting.') 41 | table_name = 'tablebasics' + self.random_data.get_random_name(6) 42 | table_service = None 43 | try: 44 | table_service = account.create_table_service() 45 | 46 | # Create a new table 47 | print('Create a table with name - ' + table_name) 48 | 49 | try: 50 | table_service.create_table(table_name) 51 | except Exception as err: 52 | print('Error creating table, ' + table_name + 'check if it already exists') 53 | 54 | # Create a sample entity to insert into the table 55 | customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '555-555-5555'} 56 | 57 | # Insert the entity into the table 58 | print('Inserting a new entity into table - ' + table_name) 59 | table_service.insert_entity(table_name, customer) 60 | print('Successfully inserted the new entity') 61 | 62 | # Demonstrate how to query the entity 63 | print('Read the inserted entity.') 64 | entity = table_service.get_entity(table_name, 'Harp', '1') 65 | print(entity['email']) 66 | print(entity['phone']) 67 | 68 | # Demonstrate how to update the entity by changing the phone number 69 | print('Update an existing entity by changing the phone number') 70 | customer = {'PartitionKey': 'Harp', 'RowKey': '1', 'email' : 'harp@contoso.com', 'phone' : '425-123-1234'} 71 | table_service.update_entity(table_name, customer) 72 | 73 | # Demonstrate how to query the updated entity, filter the results with a filter query and select only the value in the phone column 74 | print('Read the updated entity with a filter query') 75 | entities = table_service.query_entities(table_name, filter="PartitionKey eq 'Harp'", select='phone') 76 | for entity in entities: 77 | print(entity['phone']) 78 | 79 | # Demonstrate how to delete an entity 80 | print('Delete the entity') 81 | table_service.delete_entity(table_name, 'Harp', '1') 82 | print('Successfully deleted the entity') 83 | 84 | except Exception as e: 85 | if (config.IS_EMULATED): 86 | print('Error occurred in the sample. If you are using the emulator, please make sure the emulator is running.', e) 87 | else: 88 | print('Error occurred in the sample. Please make sure the account name and key are correct.', e) 89 | finally: 90 | # Demonstrate deleting the table, if you don't want to have the table deleted comment the below block of code 91 | print('Deleting the table.') 92 | if(table_service.exists(table_name)): 93 | table_service.delete_table(table_name) 94 | print('Successfully deleted the table') 95 | 96 | print('\nAzure Storage Basic Table samples - Completed.\n') -------------------------------------------------------------------------------- /tablestorageaccount.py: -------------------------------------------------------------------------------- 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 | 17 | from azure.storage import SharedAccessSignature 18 | from azure.storage.table import TableService, Entity 19 | 20 | class TableStorageAccount(object): 21 | """ 22 | Provides a factory for creating table 23 | with a common account name and connection_string. 24 | """ 25 | 26 | def __init__(self, account_name=None, connection_string=None, sas_token=None, endpoint_suffix = 'cosmosdb.windows.net', is_emulated=None): 27 | ''' 28 | :param str account_name: 29 | Storage account account name. 30 | :param str connection_string: 31 | Storage account connection string. 32 | :param str sas_token: 33 | Storage account sas token. 34 | :param str enpoint_suffix: 35 | Storage account endpoint_suffix. 36 | :param bool is_emulated: 37 | Whether to use the emulator. Defaults to False. If specified, will 38 | override all other parameters. 39 | ''' 40 | self.account_name = account_name 41 | self.connection_string = connection_string 42 | self.sas_token = sas_token 43 | self.endpoint_suffix = endpoint_suffix 44 | self.is_emulated = is_emulated 45 | 46 | def create_table_service(self): 47 | ''' 48 | Creates a TableService object with the settings specified in the 49 | TableStorageAccount. 50 | 51 | :return: A service object. 52 | :rtype: :class:`~azure.storage.table.tableservice.TableService` 53 | ''' 54 | return TableService(account_name = self.account_name, 55 | sas_token=self.sas_token, 56 | endpoint_suffix=self.endpoint_suffix, 57 | connection_string= self.connection_string, 58 | is_emulated=self.is_emulated) 59 | 60 | def is_azure_cosmosdb_table(self): 61 | return self.connection_string != None and "table.cosmosdb" in self.connection_string 62 | --------------------------------------------------------------------------------