我正在尝试向 Azure 存储发出 put 请求,基本上更改存储属性。虽然我可以按照此处的教程 https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key#Subheading2 来使 GET 请求工作。但我没有看到一个合适的方法来构造 PUT 请求。
所以,在搜索时我得到了这个,但是通过 get,can't connect to azure file service REST api by python但这又是一个 GET 请求。对于 PUT 请求,我总是收到 HTTP 403,我不确定它在哪里失败。这是链接中修改后的代码,用于描述我在代码中所做的事情。
import requests
import datetime
import hmac
import hashlib
import base64
storage_account_name = 'strtest'
storage_account_key = 'key'
api_version = '2016-05-31'
request_time = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
string_params = {
'verb': 'PUT',
'Content-Encoding': '',
'Content-Language': '',
'Content-Length': '',
'Content-MD5': '',
'Content-Type': 'application/xml',
'Date': '',
'If-Modified-Since': '',
'If-Match': '',
'If-None-Match': '',
'If-Unmodified-Since': '',
'Range': '',
'CanonicalizedHeaders': 'x-ms-date:' + request_time + '\nx-ms-version:' + api_version + '\n',
'CanonicalizedResource': '/' + storage_account_name + '/\ncomp:properties\nrestype:service'
}
string_to_sign = (string_params['verb'] + '\n'
+ string_params['Content-Encoding'] + '\n'
+ string_params['Content-Language'] + '\n'
+ string_params['Content-Length'] + '\n'
+ string_params['Content-MD5'] + '\n'
+ string_params['Content-Type'] + '\n'
+ string_params['Date'] + '\n'
+ string_params['If-Modified-Since'] + '\n'
+ string_params['If-Match'] + '\n'
+ string_params['If-None-Match'] + '\n'
+ string_params['If-Unmodified-Since'] + '\n'
+ string_params['Range'] + '\n'
+ string_params['CanonicalizedHeaders']
+ string_params['CanonicalizedResource'])
signed_string = base64.b64encode(hmac.new(base64.b64decode(storage_account_key), msg=string_to_sign.encode('utf-8'), digestmod=hashlib.sha256).digest()).decode()
headers = {
'x-ms-date' : request_time,
'x-ms-version' : api_version,
'Authorization' : ('SharedKey ' + storage_account_name + ':' + signed_string)
}
url = ('https://' + storage_account_name + '.blob.core.windows.net/?restype=service&comp=properties')
data = """<StorageServiceProperties></StorageServiceProperties>"""
r = requests.put(url, headers = headers, data = data)
print(r.content)
尝试发送的内容是 XML 格式。虽然代码可以处理 GET 请求,但 PUT 却不能。
最佳答案
除了Content-Type
之外,对于put请求,您还需要在string_params中填写Content-Length
,因为相应的 header 可能是由sdk自动设置的。
关于python - 使用共享 key 授权向 Azure 存储发出 PUT 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839744/