通过restapi从Python获取Azure队列的长度

2024-09-26 18:08:58 发布

您现在位置:Python中文网/ 问答频道 /正文

有人举过这个例子吗?在

此页介绍我尝试使用的REST API函数: https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata

本页描述授权过程。不幸的是,它似乎没有指定如何形成适合上述API函数的授权字符串: https://docs.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services

这是我尝试过的。我得到一个403“禁止”响应代码:

import base64, datetime, hashlib, hmac, requests

account_name = 'account123'
account_key = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmn=='
queue_name = 'stuff-to-process'

resource = '/{}/{}?comp=metadata'.format(account_name, queue_name)
rfc1123date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
x_headers = 'x-ms-date:' + rfc1123date
string_to_hash = 'GET\n\n\n\n' + x_headers + '\n' + resource
bytes_to_hash = bytes(string_to_hash).encode('utf-8')
decoded_key = base64.b64decode(account_key)
encoded_hash = base64.b64encode(hmac.new(decoded_key, bytes_to_hash, digestmod=hashlib.sha256).digest())

url = 'https://{}.queue.core.windows.net/{}'.format(account_name, queue_name)
headers = {
    'Authorization': 'SharedKeyLite ' + account_name + ':' + encoded_hash,
    'x-ms-date': rfc1123date
}

response = requests.get(url, params={'comp':'metadata'}, headers=headers, timeout=5)
print 'Response code was', response.status_code

Tags: tokeynamehttpsdatetimebytesqueueservice
1条回答
网友
1楼 · 发布于 2024-09-26 18:08:58

我试图重现这个问题,下面的错误响应通过print response.text显示了原因。在

<?xml version="1.0" encoding="utf-8"?>
<Error><Code>AuthenticationFailed</Code>
  <Message>Server failed to authenticate the request. Make sure the value of Authorization h
eader is formed correctly including the signature.
RequestId:927f38e8-0003-0023-76ad-c84979000000
Time:2017-05-09T10:14:33.8632801Z</Message>
  <AuthenticationErrorDetail>Authentication scheme SharedKeyLite is not supported.</AuthenticationErrorDetail>
</Error>

键是Authentication scheme SharedKeyLite is not supported.,所以请在代码的请求头Authorization中使用SharedKey而不是{},然后它就可以工作了,您可以通过response.header["x-ms-approximate-messages-count"]从responce头x-ms-approximate-messages-count中提取队列长度值

相关问题 更多 >

    热门问题