blob-upload_1.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. def run_sample():
  2. try:
  3. # Create the BlockBlobService that is used to call the Blob service for the storage account
  4. blob_service_client = BlockBlobService(
  5. account_name='accountname', account_key='accountkey')
  6. # Create a container called 'quickstartblobs'.
  7. container_name = 'quickstartblobs'
  8. blob_service_client.create_container(container_name)
  9. # Set the permission so the blobs are public.
  10. blob_service_client.set_container_acl(
  11. container_name, public_access=PublicAccess.Container)
  12. # Create Sample folder if it not exists, and create a file in folder Sample to test the upload and download.
  13. local_path = os.path.expanduser("~/Sample")
  14. if not os.path.exists(local_path):
  15. os.makedirs(os.path.expanduser("~/Sample"))
  16. local_file_name = "QuickStart_" + str(uuid.uuid4()) + ".txt"
  17. full_path_to_file = os.path.join(local_path, local_file_name)
  18. # Write text to the file.
  19. file = open(full_path_to_file, 'w')
  20. file.write("Hello, World!")
  21. file.close()
  22. print("Temp file = " + full_path_to_file)
  23. print("\nUploading to Blob storage as blob" + local_file_name)
  24. # Upload the created file, use local_file_name for the blob name
  25. blob_service_client.create_blob_from_path(
  26. container_name, local_file_name, full_path_to_file)
  27. # List the blobs in the container
  28. print("\nList blobs in the container")
  29. generator = blob_service_client.list_blobs(container_name)
  30. for blob in generator:
  31. print("\t Blob name: " + blob.name)
  32. # Download the blob(s).
  33. # Add '_DOWNLOADED' as prefix to '.txt' so you can see both files in Documents.
  34. full_path_to_file2 = os.path.join(local_path, str.replace(
  35. local_file_name ,'.txt', '_DOWNLOADED.txt'))
  36. print("\nDownloading blob to " + full_path_to_file2)
  37. blob_service_client.get_blob_to_path(
  38. container_name, local_file_name, full_path_to_file2)
  39. sys.stdout.write("Sample finished running. When you hit <any key>, the sample will be deleted and the sample "
  40. "application will exit.")
  41. sys.stdout.flush()
  42. input()
  43. # Clean up resources. This includes the container and the temp files
  44. blob_service_client.delete_container(container_name)
  45. os.remove(full_path_to_file)
  46. os.remove(full_path_to_file2)
  47. except Exception as e:
  48. print(e)