你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Python 的 Azure 表客户端库 - 版本 12.4.4

Azure 表是一种 NoSQL 数据存储服务,可通过使用 HTTP 或 HTTPS 的经过身份验证的调用从世界任何地方访问。 表根据需要缩放以支持插入的数据量,并允许使用非复杂访问来存储数据。 Azure 表客户端可用于访问 Azure 存储或 Cosmos 帐户。 本文档介绍 azure-data-tables

请注意,此包是现已弃用的 azure-cosmosdb-tables 替代包。 有关更多详细信息,请参阅 迁移指南

源代码 | 包 (PyPI) | 包 (Conda) | API 参考文档 | 样品

免责声明

对 Python 2.7 的 Azure SDK Python 包支持已于 2022 年 1 月 1 日结束。 有关详细信息和问题,请参阅 https://github.com/Azure/azure-sdk-for-python/issues/20691Python 3.7 或更高版本才能使用此包。有关更多详细信息,请参阅 适用于 Python 的 Azure SDK 版本支持策略

入门

Azure 表 SDK 可以访问 Azure 存储或 CosmosDB 帐户。

先决条件

创建帐户

安装包

使用 pip 安装适用于 Python 的 Azure 表客户端库:

pip install azure-data-tables

创建客户端

使用 Azure 表库可以与两种类型的资源进行交互:

  • 帐户中的表
  • 这些表中的实体。 与这些资源的交互从 客户端的实例开始。 若要创建客户端对象,需要帐户的表服务终结点 URL 和用于访问帐户的凭据。 endpoint可以在 Azure 门户的“访问密钥”部分下的存储帐户页面上找到,或者通过运行以下 Azure CLI 命令:
# Get the table service URL for the account
az storage account show -n mystorageaccount -g MyResourceGroup --query "primaryEndpoints.table"

获得帐户 URL 后,它可用于创建服务客户端:

from azure.data.tables import TableServiceClient
service = TableServiceClient(endpoint="https://<my_account_name>.table.core.windows.net/", credential=credential)

有关表服务 URL 以及如何为 Azure 存储配置自定义域名的详细信息,检查官方文档

凭据类型

参数 credential 可能以多种不同的形式提供,具体取决于要使用的授权类型。 表库支持以下授权:

  • 共享密钥
  • 连接字符串
  • 共享访问签名令牌
从共享密钥创建客户端

若要使用帐户 共享密钥 (又名帐户密钥或访问密钥) ,请以字符串的形式提供密钥。 可以在 Azure 门户 的“访问密钥”部分下的存储帐户中找到,也可以通过运行以下 Azure CLI 命令找到:

az storage account keys list -g MyResourceGroup -n MyStorageAccount

使用密钥作为凭据参数对客户端进行身份验证:

from azure.core.credentials import AzureNamedKeyCredential
from azure.data.tables import TableServiceClient

credential = AzureNamedKeyCredential("my_account_name", "my_access_key")

service = TableServiceClient(endpoint="https://<my_account_name>.table.core.windows.net", credential=credential)
从连接字符串创建客户端

根据用例和授权方法,你可能更喜欢使用连接字符串初始化客户端实例,而不是单独提供帐户 URL 和凭据。 为此,请将连接字符串传递给客户端的 from_connection_string 类方法。 可以在 Azure 门户 的“访问密钥”部分下的存储帐户中找到连接字符串,或者使用以下 Azure CLI 命令:

az storage account show-connection-string -g MyResourceGroup -n MyStorageAccount
from azure.data.tables import TableServiceClient
connection_string = "DefaultEndpointsProtocol=https;AccountName=<my_account_name>;AccountKey=<my_account_key>;EndpointSuffix=core.windows.net"
service = TableServiceClient.from_connection_string(conn_str=connection_string)
从 SAS 令牌创建客户端

若要使用 共享访问签名 (SAS) 令牌,请以字符串的形式提供令牌。 如果帐户 URL 包含 SAS 令牌,请省略凭据参数。 可以从 Azure 门户的 共享访问签名 下生成 SAS 令牌,或使用其中 generate_*_sas() 一个函数为帐户或表创建 sas 令牌:

from datetime import datetime, timedelta
from azure.data.tables import TableServiceClient, generate_account_sas, ResourceTypes, AccountSasPermissions
from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential

credential = AzureNamedKeyCredential("my_account_name", "my_access_key")
sas_token = generate_account_sas(
    credential,
    resource_types=ResourceTypes(service=True),
    permission=AccountSasPermissions(read=True),
    expiry=datetime.utcnow() + timedelta(hours=1),
)

table_service_client = TableServiceClient(endpoint="https://<my_account_name>.table.core.windows.net", credential=AzureSasCredential(sas_token))

关键概念

表服务的常见用途包括:

  • 存储 TB 量级的结构化数据,能够为 Web 规模应用程序提供服务
  • 存储不需要复杂联接、外键或存储过程且可取消规范化以快速访问的数据集
  • 使用聚集索引快速查询数据
  • 使用 OData 协议和 LINQ 筛选器表达式访问数据

以下组件构成 Azure 表服务:

  • 帐户
  • 帐户中的表,其中包含一组实体
  • 表中的实体,作为字典

使用适用于 Python 的 Azure 表客户端库,可以通过使用专用客户端对象来与其中每个组件进行交互。

客户端

提供了两个不同的客户端来与表服务的各个组件进行交互:

  1. TableServiceClient -
    • 获取和设置帐户设置
    • 查询、创建和删除帐户中的表。
    • 获取 以 TableClient 使用 get_table_client 方法访问特定表。
  2. TableClient -
    • 与尚不存在) 的特定表 (交互。
    • 在指定的表中创建、删除、查询和更新插入实体。
    • 创建或删除指定的表本身。

实体

实体与行类似。 实体具有 PartitionKeyRowKey、 和一组属性。 属性是名称值对,类似于列。 表中的每个实体不需要具有相同的属性。 实体可以表示为字典,如下所示作为示例:

entity = {
    'PartitionKey': 'color',
    'RowKey': 'brand',
    'text': 'Marker',
    'color': 'Purple',
    'price': '5'
}
  • create_entity - 向表添加实体。
  • delete_entity - 从表中删除实体。
  • update_entity - 通过合并或替换现有实体来更新实体的信息。
    • UpdateMode.MERGE 将向现有实体添加新属性,它不会删除现有属性
    • UpdateMode.REPLACE 将使用给定实体替换现有实体,并删除提交实体中未包含的任何现有属性
  • query_entities - 使用 OData 筛选器查询表中的现有实体。
  • get_entity - 按分区键和行键从表获取特定实体。
  • upsert_entity - 合并或替换表中的实体,或者如果该实体不存在,则插入该实体。
    • UpdateMode.MERGE 将向现有实体添加新属性,它不会删除现有属性
    • UpdateMode.REPLACE 将使用给定实体替换现有实体,并删除提交实体中未包含的任何现有属性

示例

以下部分提供了几个代码片段,涵盖了一些最常见的表任务,包括:

创建表

在帐户中创建表,并获取 以 TableClient 对新创建的表执行操作:

from azure.data.tables import TableServiceClient
table_service_client = TableServiceClient.from_connection_string(conn_str="<connection_string>")
table_name = "myTable"
table_client = table_service_client.create_table(table_name=table_name)

创建实体

在表中创建实体:

from azure.data.tables import TableServiceClient
from datetime import datetime

PRODUCT_ID = u'001234'
PRODUCT_NAME = u'RedMarker'

my_entity = {
    u'PartitionKey': PRODUCT_NAME,
    u'RowKey': PRODUCT_ID,
    u'Stock': 15,
    u'Price': 9.99,
    u'Comments': u"great product",
    u'OnSale': True,
    u'ReducedPrice': 7.99,
    u'PurchaseDate': datetime(1973, 10, 4),
    u'BinaryRepresentation': b'product_name'
}

table_service_client = TableServiceClient.from_connection_string(conn_str="<connection_string>")
table_client = table_service_client.get_table_client(table_name="myTable")

entity = table_client.create_entity(entity=my_entity)

查询实体

查询表中的实体:

from azure.data.tables import TableClient
my_filter = "PartitionKey eq 'RedMarker'"
table_client = TableClient.from_connection_string(conn_str="<connection_string>", table_name="myTable")
entities = table_client.query_entities(my_filter)
for entity in entities:
    for key in entity.keys():
        print("Key: {}, Value: {}".format(key, entity[key]))

可选配置

可选的关键字 (keyword) 参数可以在客户端和每个操作级别传入。 azure-core 参考文档 介绍了重试、日志记录、传输协议等的可用配置。

重试策略配置

实例化客户端时使用以下关键字 (keyword) 参数来配置重试策略:

  • retry_total (int) :允许的重试总数。 优先于其他计数。 retry_total=0如果不想重试请求,请传入 。 默认值为 10。
  • retry_connect (int) :重试多少个与连接相关的错误。 默认值为 3。
  • retry_read (int) :读取错误时重试的次数。 默认值为 3。
  • retry_status (int) :对错误状态代码重试多少次。 默认值为 3。
  • retry_to_secondary (bool) :是否应将请求重试到辅助数据库(如果可以)。 这只应启用 RA-GRS 帐户,并且可以处理可能过时的数据。 默认为 False

其他客户端/按操作配置

其他可选配置关键字 (keyword) 可在客户端或按操作指定的参数。

客户端关键字 (keyword) 参数:

  • connection_timeout (int) :(可选)设置连接和读取超时值(以秒为单位)。
  • 传输 (任何) :用户提供的用于发送 HTTP 请求的传输。

按操作关键字 (keyword) 参数:

  • raw_response_hook (可调用) :给定回调使用从服务返回的响应。
  • raw_request_hook (可调用) :给定的回调在发送到服务之前使用请求。
  • client_request_id (str) :请求的可选用户指定标识。
  • user_agent (str) :将自定义值追加到要随请求一起发送的用户代理标头。
  • logging_enable (bool) :在 DEBUG 级别启用日志记录。 默认为 False。 也可以在客户端级别传入,以为所有请求启用它。
  • 标头 (dict) :将自定义标头作为键值对传入。 例如 headers={'CustomValue': value}

疑难解答

常规

Azure 表客户端会引发 Azure Core 中定义的异常。 使用 Python SDK 与 Azure 表库交互时,服务返回的错误会响应 REST API 请求的相同 HTTP 状态代码。 表服务操作会在失败时引发 , HttpResponseError 并显示有用的 错误代码

例如,如果尝试创建已存在的表,则会返回指示 409 “冲突”的错误。

from azure.data.tables import TableServiceClient
from azure.core.exceptions import HttpResponseError
table_name = 'YourTableName'

service_client = TableServiceClient.from_connection_string(connection_string)

# Create the table if it does not already exist
tc = service_client.create_table_if_not_exists(table_name)

try:
    service_client.create_table(table_name)
except HttpResponseError:
    print("Table with name {} already exists".format(table_name))

日志记录

此库使用标准 日志记录 库进行日志记录。 有关 HTTP 会话 (URL、标头等的基本信息,) 在 INFO 级别记录。

可以使用 参数在客户端 logging_enable 上启用详细的调试级别日志记录,包括请求/响应正文和未处理标头:

import sys
import logging
from azure.data.tables import TableServiceClient
# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

# This client will log detailed information about its HTTP sessions, at DEBUG level
service_client = TableServiceClient.from_connection_string("your_connection_string", logging_enable=True)

同样, logging_enable 可以为单个操作启用详细日志记录,即使未为客户端启用它:

service_client.create_entity(entity=my_entity, logging_enable=True)

后续步骤

示例入门。

SDK 的 GitHub 存储库中提供了多个 Azure 表 Python SDK 示例。 这些示例提供了使用表时经常遇到的其他方案的示例代码。

常见方案

这些代码示例演示 Azure 表客户端库的常见方案操作。 示例的异步版本 (追加_async) python 示例文件显示异步操作。

其他文档

有关 Azure 表的更多文档,请参阅有关 docs.microsoft.com 的 Azure 表文档

已知问题

可在此处找到与 Cosmos DB 表终结点相关的当前已知问题列表。

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。

此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。

曝光数