python - Azure Devops Rest API 授权 header 不起作用

标签 python azure http azure-devops http-headers

我正在尝试从在 Azure Devops 上运行的虚拟机请求使用情况指标。我知道它在线,因为我发送了 ping。但是,每次我尝试运行程序并填写正确的获取信息时,都会出现错误:

{"error":{"code":"AuthenticationFailed","message":"Authentication failed. The 'Authorization' header is missing."}}

我按照此处的说明进行操作:https://learn.microsoft.com/en-us/azure/virtual-machines/linux/metrics-vm-usage-rest

import requests
BASE_URL = "GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmname}/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=Percentage%20CPU&timespan=2018-06-05T03:00:00Z/2018-06-07T03:00:00Z"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer {myPAT}"
}
response = requests.get(BASE_URL,headers)
print(response.text)

该错误存在于我的授权 header 中,我缺少什么?

编辑:实际上这个问题Is there a way to call Azure Devops via python using 'requests'?解决了我的问题,但现在我有另一个错误“{”error”:{“code”:“InvalidAuthenticationToken”,“message”:“访问 token 无效。”}}”。我正在阅读文档。 https://learn.microsoft.com/en-us/azure/active-directory-b2c/access-tokens谢谢。

最佳答案

基本上,您无法使用 Azure DevOps PAT。您需要按照以下文档创建服务主体并请求访问 token :Azure REST API Reference

使用curl很容易实现,请引用Calling Azure REST API via curl了解详情。

正如博客中提到的,如果您需要 token 来运行一些测试,并且不想创建服务主体,那么您可以运行以下命令来获取访问 token 。您将获得最长有效期为 1 小时的访问 token 。

az 帐户获取访问 token

之后,您可以在脚本中使用访问 token 。

enter image description here

关于python - Azure Devops Rest API 授权 header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62804702/

相关文章:

java - 使用 shell 命令传递 Python/JAVA/Perl 选项

php - SOAP:HTTP 错误请求

json - 使用 AZ CLI 提取应用服务计划 Azure 资源列表

swift - 如何将引号(“)包含到 Swift 中 HTTP Head 字段使用的字符串中

python - 查询python控制流语句和lambda exp

使用 MysqlDb 时出现 Python 错误 - sets 模块已弃用

javascript - 在什么情况下发出 HTTP 请求但未收到响应?

ios - 如何配置用于身份验证的 HTTP header ?

python - cx_Oracleexecutemany 与executemanyprepared

c# - Azure Functions 输出到 cosmos db