python - 尽管在 Postman 中工作,Python PUT 请求总是返回 401 错误
问题描述
所以我试图调用一个 PUT 请求来创建一个库存策略:https ://docs.microsoft.com/en-us/rest/api/storagerp/blob-inventory-policies/create-or-update
我正在使用 Ansible 自定义模块和 Python 来创建它。
Python
def create_inventory_rule(bearer_token,azure_subscription, azure_storage_account, azure_resource_group):
management_url = "https://management.azure.com/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/inventoryPolicies/default?api-version=2021-04-01".format(azure_subscription,azure_resource_group,azure_storage_account)
body= get_body()
headers = {
'Authorization': bearer_token
}
try:
request = requests.put(management_url, headers= headers, data = body)
request.raise_for_status()
except requests.exceptions.RequestException as e:
raise
我可以确认我能够获取 management_url 中的所有变量以及 Bearer 令牌。我在 ansible 运行中获取了创建的 management_url 和承载令牌,在 Postman 中使用它,它返回了 200 OK。我只是想知道我是否在这里遗漏了什么。
- name: Create Access Token
create_token:
azure_resource : "{{ azure_resource }}"
azure_tenant_id: "{{ azure_tenant_id }}"
azure_client_id: "{{ azure_client_id }}"
azure_client_secret: "{{ azure_client_secret }}"
register: c_access_token
- name: Create Inventory Policy Rule
create_inventory_rules:
bearer_token: "{{ c_access_token }}"
azure_subscription: "{{ azure_subscription }}"
azure_storage_account: "{{ azure_storage_account }}"
azure_resource_group: "{{ azure_resource_group }}"
谁能帮我在这里检查一下我真的迷路了。可能只是我忽略的东西。
获取正文:
def get_body():
body = {
"properties": {
"policy": {
"enabled": "True",
"type": "Inventory",
"rules": [
{
"enabled": "True",
"name": "inventoryPolicyRule",
"destination": "inventory-report",
"definition": {
"filters": {
"blobTypes": [
"blockBlob",
"appendBlob"
],
"prefixMatch": [
"raw",
"refined",
"produced"
],
"includeSnapshots": "True",
"includeBlobVersions": "True"
},
"format": "Csv",
"schedule": "Daily",
"objectType": "Blob",
"schemaFields": [
"Name",
"Creation-Time",
"Last-Modified",
"Content-Length",
"Content-MD5",
"BlobType",
"AccessTier",
"AccessTierChangeTime",
"Snapshot",
"VersionId",
"IsCurrentVersion",
"Metadata"
]
}
}
]
}
}
}
return body
解决方案
注册 c_access_token 后尝试添加调试。当您在 ansible 中注册时,会有一个对象,因此您需要准确定义令牌的位置。
- debug: var=c_access_token
我怀疑您在注册变量中传递的任务应该是这样的
bearer_token: "{{ c_access_token.results.someOtherObjectKey }}"
推荐阅读
- amazon-web-services - 让我们在 lightsail 资源中为 nodejs 加密 SSL
- php - 如何用 PHP 计算 HTML 代码的行数?
- c - 字符,即“a”或除 0-9 以外的任何其他字母,程序无限循环
- python - 各种日期时间格式和熊猫的困难
- python-3.x - 为请求指定接口(或源 IP)
- node.js - 错误 [ERR_HTTP_HEADERS_SENT] 未能上传图片
- python - 按字典值过滤 Pandas 系列
- java - Apache Storm - KafkaSpout 不使用来自 Kafka 主题的消息
- sql - 知道下面的 SQL 代码在做什么
- math - 如何将操作的输出保持在 2 个设定值之间?(极限,模数)