def upload_file_to_container(container_client, file_path): """ Uploads a local file to an Azure Blob storage container. :param container_client: An Azure Blob storage container client. :type container_client: `azure.storage.blob.ContainerClient` :param str file_path: The local path to the file. :rtype: `azure.batch.models.ResourceFile` :return: A ResourceFile initialized with a SAS URL appropriate for Batch tasks. """ blob_name = os.path.basename(file_path) container_props = container_client.get_container_properties() container_name = container_props["name"] print('Uploading file {} to container [{}]...'.format( file_path, container_name)) blob_client = container_client.get_blob_client(blob_name) with open(file_path, "rb") as data: blob_client.upload_blob(data, blob_type="BlockBlob") sas_token = azureblob.generate_blob_sas( config._STORAGE_ACCOUNT_NAME, container_name, blob_name, account_key=config._STORAGE_ACCOUNT_KEY, permission=azureblob.BlobSasPermissions(read=True), expiry=datetime.datetime.utcnow() + datetime.timedelta(hours=2)) sas_url = 'https://{}.blob.core.windows.net/{}/{}?{}'.format( config._STORAGE_ACCOUNT_NAME, container_name, blob_name, sas_token) return batchmodels.ResourceFile(http_url=sas_url, file_path=blob_name)
def get_url(self, blobname, write_permission=False): if write_permission: permissions = azureblob.BlobSasPermissions(read=True, write=True, create=True, delete=True) else: permissions = azureblob.BlobSasPermissions(read=True) start_time = datetime.datetime.utcnow() expiry_time = datetime.datetime.utcnow() + datetime.timedelta(hours=12) token = self.blob_service.get_user_delegation_key( key_start_time=start_time, key_expiry_time=expiry_time) sas_token = blob_sas.generate_blob_sas( self.storage_account, self.storage_container, blobname, user_delegation_key=token, permission=permissions, start=start_time, expiry=expiry_time, ) protocol = "https" primary_endpoint = "{}.blob.core.windows.net".format( self.storage_account) url = '{}://{}/{}/{}'.format( protocol, primary_endpoint, self.storage_container, blobname, ) url += '?' + sas_token return url
def url(self, channel: str, src: str, expires=3600): # expires is in seconds, so the default is 60 minutes! channel_container = self._container_map(channel) sas_token = azure.generate_blob_sas( account_name=self.storage_account_name, container_name=channel_container, blob_name=src, account_key=self.access_key, permission=azure.BlobSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(seconds=expires), ) bsc = azure.BlobServiceClient.from_connection_string(self.conn_string) blob = bsc.get_blob_client(channel_container, src) return azure.BlobClient.from_blob_url(blob.url, credential=sas_token).url