python-quick-start_3.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. def upload_file_to_container(blob_storage_service_client: BlobServiceClient,
  2. container_name: str, file_path: str) -> batchmodels.ResourceFile:
  3. """
  4. Uploads a local file to an Azure Blob storage container.
  5. :param blob_storage_service_client: A blob service client.
  6. :param str container_name: The name of the Azure Blob storage container.
  7. :param str file_path: The local path to the file.
  8. :return: A ResourceFile initialized with a SAS URL appropriate for Batch
  9. tasks.
  10. """
  11. blob_name = os.path.basename(file_path)
  12. blob_client = blob_storage_service_client.get_blob_client(container_name, blob_name)
  13. print(f'Uploading file {file_path} to container [{container_name}]...')
  14. with open(file_path, "rb") as data:
  15. blob_client.upload_blob(data, overwrite=True)
  16. sas_token = generate_blob_sas(
  17. config.STORAGE_ACCOUNT_NAME,
  18. container_name,
  19. blob_name,
  20. account_key=config.STORAGE_ACCOUNT_KEY,
  21. permission=BlobSasPermissions(read=True),
  22. expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=2)
  23. )
  24. sas_url = generate_sas_url(
  25. config.STORAGE_ACCOUNT_NAME,
  26. config.STORAGE_ACCOUNT_DOMAIN,
  27. container_name,
  28. blob_name,
  29. sas_token
  30. )
  31. return batchmodels.ResourceFile(
  32. http_url=sas_url,
  33. file_path=blob_name
  34. )