PUT-запрос к хранилищу Azure с авторизацией с общим ключом - PullRequest
0 голосов
/ 16 октября 2018

Я пытаюсь отправить запрос на хранение в хранилище Azure, в основном меняя свойства хранилища.Хотя я могу заставить работать запрос GET, следуя инструкциям здесь https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key#Subheading2, но я не вижу подходящего для создания запроса PUT там.

Итак, при поиске я получил это, но с помощью get, не может подключиться к API-интерфейсу REST файловой службы Azure с помощью 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 нет.

Ответы [ 2 ]

0 голосов
/ 17 октября 2018

Вот рабочий код.

import requests
import datetime
import hmac
import hashlib
import base64

storage_account_name = 'acc_name'
storage_account_key = 'ac_key'
api_version = '2018-03-28'
request_time = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
data = "<StorageServiceProperties></StorageServiceProperties>"
content_len = str(len(data))

string_params = {
    'verb': 'PUT',
    'Content-Encoding': '',
    'Content-Language': '',
    'Content-Length': content_len,
    '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,
    'Content-Type': 'application/xml',
    'Content-Length': content_len,
    '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)
0 голосов
/ 17 октября 2018

Помимо Content-Type, для запроса на размещение вам также необходимо заполнить Content-Length в string_params, так как соответствующий заголовок, вероятно, устанавливается sdk автоматически.

...