有几个关于使用 Azure AD 访问 Azure Blob 的 Azure 官方文档,如下所示。
-
Authorize access to Azure blobs and queues using Azure Active Directory
- Authorize access to blobs and queues with Azure Active Directory from a client application
-
Authorize with Azure Active Directory 关于授权对 Azure 存储的请求
平均而言,这是我获取 Azure 存储帐户的密钥(帐户密码)以在数据块中使用它的示例代码。
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.storage import StorageManagementClient
# Please refer to the second document above to get these parameter values
credentials = ServicePrincipalCredentials(
client_id='<your client id>',
secret='<your client secret>',
tenant='<your tenant id>'
)
subscription_id = '<your subscription id>'
client = StorageManagementClient(credentials, subscription_id)
resource_group_name = '<the resource group name of your storage account>'
account_name = '<your storage account name>'
# print(dir(client.storage_accounts))
keys_json_text = client.storage_accounts.list_keys(resource_group_name, account_name, raw=True).response.text
import json
keys_json = json.loads(keys_json_text)
# print(keys_json)
# {"keys":[{"keyName":"key1","value":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==","permissions":"FULL"},{"keyName":"key2","value":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==","permissions":"FULL"}]}'
key1 = keys_json['keys'][0]['value']
print(key1)
然后,您可以使用上面的账号密码按照Azure Databricks官方文档Data > Data Sources > Azure Blob Storage读取数据。
否则,您可以参考我的回答中的步骤 1 和 2 让另一个 SO 线程 transform data in azure data factory using python data bricks 读取数据,如下面的代码。
from azure.storage.blob.baseblobservice import BaseBlobService
from azure.storage.blob import ContainerPermissions
from datetime import datetime, timedelta
account_name = '<your account name>'
account_key = '<your account key>' # the key comes from the code above
container_name = '<your container name>'
service = BaseBlobService(account_name=account_name, account_key=account_key)
token = service.generate_container_shared_access_signature(container_name, permission=ContainerPermissions.READ, expiry=datetime.utcnow() + timedelta(hours=1),)
blob_name = '<your blob name of dataset>'
blob_url_with_token = f"https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}?{token}"
import pandas as pd
pdf = pd.read_json(blob_url_with_token)
df = spark.createDataFrame(pdf)