Search code examples
pythonazureazure-storageazure-blob-storage

Importing azure blob via SAS in Python


EDIT: I am looking to import a blob from an Azure Storage Container into my Python script via a BLOB-specific SAS.

from azure.storage.blob import BlobService

sas_service = BlobService(
    account_name = "name",
    sas_token = "mytoken"
)

blob_content = sas_service.get_blob_to_path("container_name", "blob_name")

I tried using this, but it outputs an OSError listing also a "503 error"


Solution

  • According to your description , you want to access azure blob storage via SAS_TOKEN.

    You could refer to the snippet of code as below which works for me:

    from datetime import datetime, timedelta
    import requests
    from azure.storage.blob import (
        BlockBlobService,
        ContainerPermissions,
    )
    
    accountName = "<your_account_name>"
    accountKey = "<your_account_key>"
    containerName = "<your_container_name>"
    blobName = "<your_blob_name>"
    
    def GetSasToken():
        blobService = BlockBlobService(account_name=accountName, account_key=accountKey)
        sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1))
        return sas_token
    
    
    def AccessTest(token):
        blobService = BlockBlobService(account_name = accountName, account_key = None, sas_token = token)
        blobService.get_blob_to_path(containerName,blobName,"E://test.txt")
    
    
    token=GetSasToken()
    print token
    AccessTest(token)
    

    You could also refer to more details from official tutorial.

    Hope it helps you.