gpt4 book ai didi

python - 如何在 python 中为 cosmos db 生成其余授权 token ?

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:12 25 4
gpt4 key购买 nike

我在为简单的获取数据库请求生成 cosmos db 的授权 token 时遇到问题。这是我的 Python 代码:

import requests
import hmac
import hashlib
import base64
from datetime import datetime

key = 'AG . . .EZPcZBKz7gvrKiXKsuaPA=='
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
payload = ('get\ndbs\n\n' + now + '\n\n').lower()
signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()

url = 'https://myacct.documents.azure.com/dbs'
headers = {
'Authorization': "type=master&ver=1.0&sig=" + signature,
"x-ms-date": now,
"x-ms-version": "2017-02-22"
}

res = requests.get(url, headers = headers)
print res.content

产生此错误的原因:

{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ndbs\n\nsun, 08 apr 2018 02:39:00 gmt\n\n'\r\nActivityId: 5abe59d8-f44e-42c1-9380-5cf4e63425ec, Microsoft.Azure.Documents.Common/1.21.0.0"}

最佳答案

格雷格。根据我的观察,您的代码遗漏了 url encode。您可以找到示例代码 here .

请引用我的代码,我的代码对你的代码做了一些微调。

import requests
import hmac
import hashlib
import base64
from datetime import datetime
import urllib

key = '***'
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
print now
payload = ('get\ndbs\n\n' + now + '\n\n').lower()

payload = bytes(payload).encode('utf-8')
key = base64.b64decode(key.encode('utf-8'))

signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()
print signature

authStr = urllib.quote('type=master&ver=1.0&sig={}'.format(signature))
print authStr

headers = {
'Authorization': authStr,
"x-ms-date": now,
"x-ms-version": "2017-02-22"
}
url = 'https://***.documents.azure.com/dbs'
res = requests.get(url, headers = headers)
print res.content

执行结果:

enter image description here

希望对你有帮助。

关于python - 如何在 python 中为 cosmos db 生成其余授权 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com