如何格式化标头以使用python-requests发送

时间:2016-03-07 10:23:34

标签: python http-headers python-requests

我不确定如何按headers中的示例中的字母顺序获取python-requests。括号和标点符号如“发送时影响请求标题?”

这是我的代码:

headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback", 
          'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
          'oauth_version': "1.0",
          'oauth_timestamp': time, #int(time.time()),
          'oauth_nonce' : nonce,
          'oauth_signature_method' : "HMAC-SHA1",
          'oauth_signature' : signature
          }


authorization = ', '.join([key + '="' + urllib.parse.quote_plus(str(value)) + '"' for key, value in headers.items()])
http_headers = {'Authorization': authorization}

输出是:

  {'Authorization': 'oauth_nonce="62942100", oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%252Ftrademe-callback", oauth_consumer_key="5C82CC6BC7C6472154FBC9CAB24A29A2", oauth_version="1.0", oauth_timestamp="1457345962", oauth_signature="b%27o0rNPtba78EQ3ALsg2mX1Y4vIQw%3D%27", oauth_signature_method="HMAC-SHA1"'}

示例中定义的输出:

  

要制作Authorization标头,只需附加所有值即可   以“OAuth”开头。每个值都必须进行URL编码。

  Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.website-tm-access.co.nz%2Ftrademe-callback", oauth_consumer_key="C74CD73FDBE37D29BDD21BAB54BC70E422", oauth_version="1.0", oauth_timestamp="1285532322", oauth_nonce="7O3kEe", oauth_signature_method="HMAC-SHA1", oauth_signature="5s3%2Bel078a5AXGi43FBDyfg5yWY%3D"

1 个答案:

答案 0 :(得分:0)

将标题传递给requests模块时,顺序不重要。

你可以这样做:

headers = {'oauth_callback': "http://www.website-tm-access.co.nz%2Ftrademe-callback", 
          'oauth_consumer_key' : "5C82CC6BC7C6472154FBC9CAB24A29A2" ,
          'oauth_version': "1.0",
          'oauth_timestamp': int(time.time()),
          'oauth_nonce' : nonce,
          'oauth_signature_method' : "HMAC-SHA1",
          'oauth_signature' : signature
          }
r = requests.get(url, headers=headers)