Azure-blob-storage.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from azure.storage.blob import BlobClient, BlobServiceClient
  2. import os
  3. import requests
  4. def list_files() -> list:
  5. file_list = []
  6. for root, dirs, files in os.walk("data"):
  7. for name in files:
  8. file_list.append({"file_name": name, "local_path": os.path.join(root,name)})
  9. return file_list
  10. def get_filename_from_url(url: str) -> str:
  11. file_name=url.split('/')[-1]
  12. return file_name
  13. def get_random_images() -> list:
  14. # helper function uses loremflickr.com to get a random list of images
  15. images = []
  16. for i in range(10):
  17. resp = requests.get(url=f"https://loremflickr.com/json/320/240?random={i}")
  18. resp_json = resp.json()
  19. images.append(resp_json["file"])
  20. return images
  21. def create_blob_from_url(storage_connection_string,container_name):
  22. try:
  23. # urls to fetch into blob storage
  24. url_list = get_random_images()
  25. # Instantiate a new BlobServiceClient and a new ContainerClient
  26. blob_service_client = BlobServiceClient.from_connection_string(storage_connection_string)
  27. container_client = blob_service_client.get_container_client(container_name)
  28. for u in url_list:
  29. # Download file from url then upload blob file
  30. r = requests.get(u, stream = True)
  31. if r.status_code == 200:
  32. r.raw.decode_content = True
  33. blob_client = container_client.get_blob_client(get_filename_from_url(u))
  34. blob_client.upload_blob(r.raw,overwrite=True)
  35. return True
  36. except Exception as e:
  37. print(e.message, e.args)
  38. return False
  39. def create_blob_from_path(storage_connection_string,container_name):
  40. try:
  41. # Instantiate a new BlobServiceClient and a new ContainerClient
  42. blob_service_client = BlobServiceClient.from_connection_string(storage_connection_string)
  43. container_client = blob_service_client.get_container_client(container_name)
  44. for f in list_files():
  45. with open(f["local_path"], "rb") as data:
  46. blob_client = container_client.get_blob_client(f["file_name"])
  47. blob_client.upload_blob(data,overwrite=True)
  48. return True
  49. except Exception as e:
  50. print(e.message, e.args)
  51. return False
  52. if __name__ == '__main__':
  53. # get storage account settings
  54. storage_connection_string = os.environ.get("STORAGE_CONNECTION_STRING")
  55. container_name = os.environ.get("STORAGE_CONTAINER")
  56. # # if you want to copy from a public url
  57. result = create_blob_from_url(storage_connection_string,container_name)
  58. # OR if you want to upload form your local drive
  59. #create_blob_from_path(storage_connection_string,container_name)
  60. if(result):
  61. print("Done!")
  62. else:
  63. print("An error occured!")