我正在尝试使用 Python 从 REST API 中获取信息,它需要 OAuth 标识。我已经设法用 Postman 编写请求并且它有效。然而,Postman 给我的 python 代码不起作用:
import requests
url = "https://www.somewebsite.com/api/rest/products/store/2"
querystring = {"limit":"100","page":"5"}
headers = {
'Authorization': "OAuth oauth_consumer_key="3626311748bcf2072da2bd475fccfa3c",\
oauth_token="878c7c0eb6122e6208b75e2ba9e23f86",\
oauth_signature_method="HMAC-SHA1",oauth_timestamp="1560892926",\
oauth_nonce="9Cy9wmOo21v",oauth_signature="9VqTR2qFQLZ%2Fz2Ibvny1e%2BC7Zes%3D"",
'User-Agent': "PostmanRuntime/7.15.0",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Postman-Token': "eef345cc-52ee-4496-8109-e7ea013adb9c,0834423c-041c-4ca5-8bef-33876c311ef6",
'Host': "www.inart.com",
'cookie': "PHPSESSID=gmjmllng429gfk8t0hvd1abbu3",
'accept-encoding': "gzip, deflate",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)
不工作的部分实际上是随机数、时间戳和签名。我创建了一个生成随机数和随机时间戳的函数,但我不知道如何为 HMAC-SHA1 生成有效签名。 是否有一个库可以为我进行身份验证,或者我是否需要编写自己的函数来生成有效签名?签名取决于整个调用还是仅取决于随机数、时间戳和 token 等部分? 任何帮助将不胜感激!
最佳答案
你可以查看这个库
https://requests-oauthlib.readthedocs.io/en/latest/ 。
它同时支持 Oauth1 和 Oauth2,并提供丰富的文档。无需关心创建随机数、时间戳以及 oauth_signature。只需提供您的 app_key、app_secret、request_token_url、authorization_url 和 access_token_url。
关于python - 如何使用 python 使用 hmac-sha1 生成 oauth 签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56657291/