如何使用restapi查询Azure表存储

2024-09-26 22:09:27 发布

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

我想访问我在azure存储帐户中的表。在

import requests

import hashlib

import base64

import hmac

import datetime
storageAccountName = 'rishistorage1234' # your storage account name
storageKey='my-account-key'# your storage account access key
url = 'https://' + storageAccountName + '.table.core.windows.net/table1'
version = '2016-05-31' # x-ms-version
date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")  #x-ms-date
parameters = 'table1'
CanonicalizedResources = '/' + storageAccountName + '/' + parameters
CanonicalizedHeaders = 'x-ms-date:' + date 
stringToSign = 'GET\n\n\n\n\n' + CanonicalizedHeaders + '\n' + CanonicalizedResources
# note the b64decode of the storageKey
signature = base64.b64encode(hmac.new(base64.b64decode(storageKey), 
msg=stringToSign, digestmod=hashlib.sha256).digest())
headers = {'x-ms-date': date,
     'x-ms-version': version,
       'Authorization': 'SharedKeyLite ' + storageAccountName + ':' + 
signature}

# send the request
#print signature
response = requests.get(url, headers=headers)
print response
print response.headers
print response.content

抱歉,我不能复制所有的“代码”,请忽略缩进错误。 表的名称是table1 历史记录1234的存储名为RAG134 访问键1是my-account-key。在

我得到的答复是

^{pr2}$

Tags: thekeyimportdatetimedateversionresponseaccount
2条回答

根据您的错误信息和代码,我确信该问题是由于对Azure表服务使用了SharedKeyLite中不正确的StringToSign格式,即您的StringToSign格式是针对Blob的,而不是针对表的,如下所示。在

您的错误代码和信息属于AuthenticationFailed,请参见here。在

enter image description here

Azure表服务的正确StringToSign格式应该如下所示,比如StringToSign = Date + "\n"+ CanonicalizedResource。在

enter image description here

如果有人正在寻找使用restapi从azure表存储查询表的python代码,下面是代码

import requests

import hashlib

import base64

import hmac

import datetime
storageAccountName = 'my-account-name' # your storage account name
storageKey='my-account-key'# your storage account access key
url = 'https://' + storageAccountName + '.table.core.windows.net/table-name'
version = '2016-05-31' # x-ms-version
date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")  #x-ms-date
parameters = 'table-name'
CanonicalizedResources = '/' + storageAccountName + '/' + parameters
CanonicalizedHeaders = 'x-ms-date:' + date 
stringToSign = date + '\n' + CanonicalizedResources
# note the b64decode of the storageKey
signature = base64.b64encode(hmac.new(base64.b64decode(storageKey), 
msg=stringToSign, digestmod=hashlib.sha256).digest())
headers = {'x-ms-date': date,
       'x-ms-version': version,
       'Authorization': 'SharedKeyLite ' + storageAccountName + ':' + 
        signature,
       'Accept': 'application/json;odata=nometadata '}

# send the request
#print signature
response = requests.get(url, headers=headers)
print response
print response.headers
print response.content

更多操作请参考 https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/table-service-rest-api

相关问题 更多 >

    热门问题