Created
June 24, 2019 07:58
-
-
Save moraisaugusto/858ef1ad37e19c224bba90ae79001bc3 to your computer and use it in GitHub Desktop.
Create a Azure Blob Storage Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os, uuid, sys | |
from azure.storage.blob import BlockBlobService, PublicAccess | |
def run_sample(): | |
try: | |
# Create the BlockBlockService that is used to call the Blob service for the storage account | |
block_blob_service = BlockBlobService( | |
account_name='ACCOUNTNAME', | |
account_key='ACCOUNTKEY' | |
) | |
# Create a container called 'quickstartblobs'. | |
container_name ='BLOBCONTAINERNAME' | |
block_blob_service.create_container(container_name) | |
# Set the permission so the blobs are public. | |
block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container) | |
# Create a file in Documents to test the upload and download. | |
inputdir = "/home/USERNAME/azureStorage/to_upload" | |
local_path=os.path.expanduser(inputdir) | |
# # go though all files in to_upload directory | |
for local_file_name in os.listdir(inputdir): | |
full_path_to_file =os.path.join(local_path, local_file_name) | |
print("\nUploading to Blob storage as blob" + local_file_name) | |
block_blob_service.create_blob_from_path(container_name, local_file_name, full_path_to_file) | |
# 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) | |
# Download the blob(s). | |
# Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents. | |
output_dir = "/home/USERNAME/azureStorage/to_download" | |
for local_file_name in os.listdir(inputdir): | |
local_path_download = os.path.join(output_dir, str.replace(local_file_name ,'.txt', '_DOWNLOADED.txt')) | |
print("\nDownloading blob to " + local_path_download) | |
block_blob_service.get_blob_to_path(container_name, local_file_name, local_path_download) | |
sys.stdout.write("Sample finished running.") | |
sys.stdout.flush() | |
input() | |
except Exception as e: | |
print(e) | |
# Main method. | |
if __name__ == '__main__': | |
run_sample() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment