Reputation: 305
I am about to write my first python program to read/write remote azure storage blob (block blob). I did some research. It is as if the storage "connection string" is absolutely mandatory. In another word, the Microsoft client-side python library requires a "connection-string" created by the storage account in order to gain access to the remote blob.
In order to keep everything as simple as possible, I am hoping that I can write a small python code to invoke an HTTP GET/PUT method (for accessing the remote azure blob storage resource) without touching the "connection string" generated by the storage account. Yet, it doesn't seem to be possible after reading Microsoft storage documentation.
Can anyone make any comment to shed any light? Thanks in advance.
Upvotes: 4
Views: 6086
Reputation: 7473
SAS token is generated by account_name and account_key. Both them are in the connection string too.
With SAS token:
from datetime import datetime, timedelta
from azure.storage.blob import BlobServiceClient, generate_account_sas, ResourceTypes, AccountSasPermissions
sas_token = generate_account_sas(
account_name="<storage-account-name>",
account_key="<account-access-key>",
resource_types=ResourceTypes(service=True),
permission=AccountSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)
blob_service_client = BlobServiceClient(account_url="https://<my_account_name>.blob.core.windows.net", credential=sas_token)
So you could access with Azure AD Access token based on service principal.
With Azure AD Access token:
from azure.common.credentials import ServicePrincipalCredentials
from azure.storage.blob import BlockBlobService
from azure.storage.common import TokenCredential
TENANT_ID = "xxxxxx"
CLIENT_ID = "xxxxxx"
CLIENT_SECRET = "xxxxxx"
RESOURCE = "https://storage.azure.com/"
credentials = ServicePrincipalCredentials(
client_id = CLIENT_ID,
secret = CLIENT_SECRET,
tenant = TENANT_ID,
resource = RESOURCE
)
token_credential = TokenCredential(credentials.token["access_token"])
ACCOUNT_NAME = "pamelastorage123"
CONTAINER_NAME = "pamelac"
blobService = BlockBlobService(account_name=ACCOUNT_NAME, token_credential=token_credential)
blob = blobService.get_blob_to_text(CONTAINER_NAME, "test.txt")
print(blob.content)
Note: plz follow these steps to assign Storage Blob Data Contributor
role and register an application first.
For more information about authentication, see here.
Upvotes: 5