2016-02-22 62 views
0

想知道如何对我的参数进行网址编码,是吗?网址编码参数

params = {'oauth_version': "1.0", 
       'oauth_nonce': oauth.generate_nonce(), 
       'oauth_timestamp': int(time.time()), 
       'oauth_consumer_key': CONSUMER_KEY, 
       'oauth_token': access_key, 
       'oauth_nonce' : nonce, 
       'oauth_consumer_key': consumer.key, 
       'oauth_signature': 'el078a5AXGi43FBDyfg5yWY', 
       } 

按照这份指南:

To make the Authorization header, you simply append all the values starting with “OAuth”. Each value must be URL encoded.

> 1. 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" 
+0

*“这是正确的吗?”* - ...它工作吗? – jonrsharpe

+3

可能重复[如何在python中对url参数进行百分比编码?](http://stackoverflow.com/questions/1695183/how-to-percent-encode-url-parameters-in-python) –

+0

我看到参数,但我不明白你是如何对它们进行URL编码的。 – jwodder

回答

0

您应该使用urllib.quote_plus或urllib.parse.quote_plus在Python 3,这将处理它很好地为您服务。

你想从您的PARAMS构建你的授权头的方法如下:

(python3版)

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

(python2版)

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

不过,您可以想看看现有的实现,比如request-oauth1。见here

+0

嗨, 我得到TypeError:quote_from_bytes()期望的字节 – musss

+1

尝试确保在params字典中的所有值转换为字符串 –

+0

我应该尝试for语句并将列表中的列转换为str(i)? – musss