我正在尝试在函数应用程序中编写一个函数来操作 CosmosDB 中的数据。如果我将读写键放入环境变量中,我就能正常工作。为了使其更加强大,我希望它能够作为托管身份应用程序运行。该应用程序在 Cosmos DB 上具有“DocumentDB 帐户贡献者”角色。
但是,CosmosClient 构造函数不接受 Credential,并且需要读写密钥。我一直在追寻 azure.mgmt.cosmosdb.operations 的兔子洞,其中有一个DatabaseAccountsOperations
类与list_keys()
方法。但我找不到访问该功能的简洁方法。如果我尝试创建该对象(这需要从我的 dbmgmt 对象中窃取配置、序列化器和反序列化器),它仍然需要resourceGroupName
and accountName
.
我情不自禁地认为我在某个地方转错了方向,因为这必须以更直接的方式实现。特别是考虑到 JavaScript SDK 引用了一个更符合逻辑的类CosmosDB管理客户端 https://learn.microsoft.com/en-us/javascript/api/@azure/arm-cosmosdb/cosmosdbmanagementclient与 SubscriptionClient 一致。但是,我在 python 端的任何地方都找不到该类。
有什么指点吗?
from azure.identity import DefaultAzureCredential
from azure.cosmos import CosmosClient
from azure.mgmt.resource import SubscriptionClient
from azure.mgmt.cosmosdb import CosmosDB
from .cred_wrapper import CredentialWrapper
def main(req: func.HttpRequest) -> func.HttpResponse:
request_body = req.get_body()
# credential = DefaultAzureCredential()
# https://gist.github.com/lmazuel/cc683d82ea1d7b40208de7c9fc8de59d
credential = CredentialWrapper()
uri = os.environ.get('cosmos-db-uri')
# db = CosmosClient(url=uri, credential=credential) # Doesn't work, wants a credential that is a RW/R key
# Does work if I replace it with my primary / secondary key but the goal is to remove dependence on that.
subscription_client = SubscriptionClient(credential)
subscription = next(subscription_client.subscriptions.list())
dbmgmt = CosmosDB(credential, subscription.subscription_id) # This doesn't accept the DB URI??
operations = list(dbmgmt.operations.list()) # I see the list_keys() Operation there...
EDIT
一个乐于助人的灵魂在这里提供了回应,但在我做出反应或接受它作为答案之前将其删除。他们指出,有一个等价的蟒蛇SDK https://learn.microsoft.com/en-us/python/api/azure-mgmt-cosmosdb/azure.mgmt.cosmosdb.cosmosdbmanagementclient?view=azure-python然后from azure.mgmt.cosmosdb import CosmosDBManagementClient
就可以了。
从那时起,我就只能靠自己了,这导致了
ImportError: cannot import name 'CosmosDBManagementClient' from 'azure.mgmt.cosmosdb'
我相信问题的根源在于软件包的不兼容azure-mgmt
。移除后azure-mgmt
从我的requirements.txt
并且仅加载cosmos和identity相关的包,导入错误得到解决。
这解决了90%的问题。
dbmgmt = CosmosDBManagementClient(credential, subscription.subscription_id, c_uri)
print(dbmgmt.database_accounts.list_keys())
TypeError: list_keys() missing 2 required positional arguments: 'resource_group_name' and 'account_name'
真的需要收集这些参数吗?相比于从 Vault 读取机密的示例 https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate#authenticate-with-defaultazurecredential看起来好复杂。