-
Notifications
You must be signed in to change notification settings - Fork 3
IOT Team Task #13: Console application that uploads a file to Azure Storage blob
Maria Kalusz edited this page Mar 20, 2020
·
10 revisions
-
Create a folder for the file and the data - you can use these command lines
- mkdir blob-filestorage
- add the python code below to this folder
- cd blob-filestorage
- mkdir data
-
Make sure you have python installed 2.7, 3.5 or above
-
Install the Azure dependency below (for MAC, put sudo in front)
- pip install azure-storage-blob
-
To connect the app to the Azure storage account, enter the following in the command line. You can find the connection string in the Azure storage account. It is also in the Python file.
- Windows setx AZURE_STORAGE_CONNECTION_STRING ""
- Linux export AZURE_STORAGE_CONNECTION_STRING=“"
- macOS export AZURE_STORAGE_CONNECTION_STRING=“”
-
Restart any running programs you have
-
To check your azure installation, enter the command below. It will list your dependencies.
- pip list
-
Run the python code in the folder. You should see a file blob added to the container in the Azure Storage account
import os, uuid, sys from azure.storage.blob import BlockBlobService, BlobPermissions def run_upload(): try: connect_str = os.getenv('AZURE_CONNECTION_STRING') # Create the BlockBlockService that is used to call the Blob service for the storage account block_blob_service = BlockBlobService(account_name='AZURE_ACCOUNT_NAME', account_key='AZURE_ACCOUNT_KEY') #blob_service_client = BlobServiceClient.from_connection_string(connect_str) container_name='AZURE_CONTAINER_NAME' BlobPermissions(read=False, add=False, create=False, write=False, delete=False, _str=None) # Create a file in local Documents directory to upload and download local_path = "./data" local_file_name = "test" + str(uuid.uuid4()) + ".txt" upload_file_path = os.path.join(local_path, local_file_name) # Write text to the file file = open(upload_file_path, 'w') file.write("test") file.close() print("\nUploading to Azure Storage as blob:\n\t" + local_file_name) #Upload the created file, use local_file_name for the blob name block_blob_service.create_blob_from_path(container_name, local_file_name, upload_file_path) # List the blobs in the container print("\nList blobs in the container") generator = block_blob_service.list_blobs(container_name) for blob in generator: print("\t Blob name: " + blob.name) except Exception as e: print(e) if __name__ == '__main__': run_upload()