【问题标题】:Python InvalidHeader error when trying to send http requests to Azure REST API尝试将 http 请求发送到 Azure REST API 时出现 Python InvalidHeader 错误
【发布时间】:2020-04-09 02:15:41
【问题描述】:

我正在尝试创建一个 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)

【问题讨论】:

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


    【解决方案1】:

    基本上,Authorization 令牌的值应采用以下格式:Bearer &lt;access-token-value&gt; 但是您传递的是 _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}
    

    【讨论】:

      猜你喜欢
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 2011-06-05
      • 1970-01-01
      • 2022-06-23
      • 2019-05-29
      • 2020-09-18
      相关资源
      最近更新 更多