尝试将HTTP请求发送到Azure REST API时出现Python InvalidHeader错误

时间:2020-04-09 02:15:41

标签: python azure rest python-requests http-headers

我正在尝试创建一个http put请求,以使用Azure REST API使用通过HTML表单创建的参数来创建资源组。尝试发送请求时,我收到一条错误消息,指出我的标题对授权标题无效。

这是我收到的错误

Exception has occurred: InvalidHeader
Value for header {Authorization: {'access_token': 'MYACCESSTOKEN', 'token_type': 'Bearer', 'expires_in': 583}} must be of type str or bytes, not <class 'dict'>

这是我的代码

@app.route('/storageaccountcreate', methods = ['POST', 'PUT'])
def storageaccountcreate():
    name = request.form['storageaccountname']
    resourcegroup = request.form['resourcegroup']
    subscriptionId = request.form['subscriptionId']
    location = request.form['location']
    sku = request.form['sku']
    headers = {"Authorization": _get_token_from_cache(app_config.SCOPE)}
    url = f'https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourcegroup}/providers/Microsoft.Storage/storageAccounts/{name}?api-version=2019-06-01'
    r = requests.put(url, headers=headers)
    print(r.text)
    return(r.text)

1 个答案:

答案 0 :(得分:1)

基本上,Authorization令牌的值应采用以下格式:Bearer <access-token-value>,但是您正在传递_get_token_from_cache方法的结果,因此会出现此错误。

要解决此问题,请从此方法的结果中获取access_tokentoken_type的值,并使用我上面指定的格式创建Authorization令牌。像这样:

token_information = _get_token_from_cache(app_config.SCOPE)
token_type = token_information['token_type']
access_token = token_information['access_token']
auth_header = token_type + " " + access_token
headers = {"Authorization": auth_header}