我不能 100% 确定所有的细微差别,但经过广泛的研究和反复试验,我得到了这个为自己工作。请随时添加建议。
import requests
import time
import random
import string
import oauthlib.oauth1.rfc5849.signature as oauth
from urllib.parse import quote_plus
import os
import json
import datetime
def create_nonce(N = 32): # randomly generated 32 character (recommended) string
result = ''.join(random.choices(string.ascii_letters + string.digits, k = N))
return result
def create_signature(httpMethod, url, urlSuffix, nonce, timestamp, consumerKey, signatureMethod, version):
consumerSecret = <INSERT_YOUR_CONSUMER_SECRET_HERE>
# https://stackoverflow.com/a/39494701/5548564
# In case of http://example.org/api?a=1&b=2 - the uri_query value would be "a=1&b=2".
uri_query = urlSuffix
# The oauthlib function 'collect_parameters' automatically ignores irrelevant header items like 'Content-Type' or
# 'oauth_signature' in the 'Authorization' section.
headers = {
"Authorization": (
f'OAuth realm="", '
f'oauth_nonce={nonce}, '
f'oauth_timestamp={timestamp}, '
f'oauth_consumer_key={consumerKey}, '
f'oauth_signature_method={signatureMethod}, '
f'oauth_version={version}')}
# There's no POST data here - in case it was: x=1 and y=2, then the value would be '[("x","1"),("y","2")]'.
data = []
params = oauth.collect_parameters(uri_query=uri_query,
body=data,
headers=headers,
exclude_oauth_signature=True,
with_realm=False)
norm_params = oauth.normalize_parameters(params)
base_string = oauth.construct_base_string(httpMethod, url, norm_params)
signature = oauth.sign_hmac_sha1(base_string, consumerSecret, '')
return quote_plus(signature)
def send_request():
url = <INSERT_URL_HERE>
urlSuffix = "_labels=1" # Addes array at end of json results including a map to the field labels
httpMethod = "GET"
consumerKey = <INSERT_CONSUMER_KEY_HERE>
signatureMethod = "HMAC-SHA1"
timestamp = str(int(time.time()))
nonce = create_nonce()
version = "1.0"
signature = create_signature(httpMethod, url, urlSuffix, nonce, timestamp, consumerKey, signatureMethod, version)
queryString = {"oauth_consumer_key": consumerKey,
"oauth_signature_method": signatureMethod,
"oauth_timestamp": timestamp,
"oauth_nonce": nonce,
"oauth_version": version,
"oauth_signature": signature}
headers = {'User-Agent': "Testing/0.1",
'Accept': "*/*",
'Host': "<INSERT_YOUR_DOMAIN_HERE>",
'Accept-Encoding': "gzip, deflate",
'Connection': "keep-alive"}
if urlSuffix:
url = url + "?" + urlSuffix
r = requests.request(httpMethod, url, headers=headers, params=queryString)
if r.status_code == 200:
dict = json.loads(r.text)
return dict
else:
print(r.status_code)
return None
response = send_request()