我如何对此进行URL编码

时间:2016-03-07 08:05:33

标签: python

需要这个:

POST&https%3A%2F%2Fsecure.trademe.co.nz%2FOauth%2FRequestToken&oauth_callback%3Dhttp%253A%252F%252Fwww.website-tm-access.co.nz%252Ftrademe-callback%26oauth_consumer_key%3DC74CD73FDBE37D29BDD21BAB54BC70E422%26oauth_nonce%3D7O3kEe%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1285532322%26oauth_version%3D1.0%26scope%3DMyTradeMeRead%252CMyTradeMeWrite

Myattempt:

New_base_string ="POST&https%3A%2F%2Fsecure.trademe.co.nz%2FOauth%2FRequestToken&oauth_callback%3Dhttp%253A%252F%252Fwww.website-tm-access.co.nz%252Ftrademe-callback%26oauth_consumer_key%" + str(consumer_key) +"3DC74CD73FDBE37D29BDD21BAB54BC70E422%26oauth_nonce%3" + str(nonce) + "%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3" + str(time) + "%26oauth_version%3D1.0%26scope%3DMyTradeMeRead%252CMyTradeMeWrite"

我只是尝试将其附加到最后,这是否可行或者我是否需要附加到列表然后进行编码?

所以这样:

headers = { my_variable + other_variable }

authorization = '5C82CC6BC7C6472154FBC9CAB24A29A2 ' + ', '.join([key + '="' + urllib.parse.quote_plus(str(value)) + '"' for key, value in headers.items()])

1 个答案:

答案 0 :(得分:1)

一般

如果您想将参数URL编码到POST请求,最好的方法是:

import urllib

f = { 'eventName' : 'myEvent', 
      'eventDescription' : 'cool event', 
      'url' : 'http://www.google.com'}

print 'POST&%s' % urllib.urlencode(f)

<强>输出:

POST&eventName=myEvent&url=http%3A%2F%2Fwww.google.com&eventDescription=cool+event

如果你想订购它而没有订购字典,只需使用一个列表

import urllib

f = [ ('eventName', 'myEvent'), 
      ('eventDescription', 'cool event'), 
      ('url', 'http://www.google.com')]

print 'POST&%s' % urllib.urlencode(f)

<强>输出

POST&eventName=myEvent&eventDescription=cool+event&url=http%3A%2F%2Fwww.google.com

如何满足您的需求(Python 3.5)

虽然在python 2.7中测试了一般示例,但我使用python 3.5代码编写了您的示例。

import urllib.parse

method = "POST"
url = "https://secure.trademe.co.nz/Oauth/RequestToken"

params = [('oauth_callback', 'http://www.website-tm-access.co.nz/trademe-callback'),
            ('oauth_consumer_key', 'C74CD73FDBE37D29BDD21BAB54BC70E422'),
            ('oauth_nonce', '7O3kEe'),
            ('oauth_signature_method', 'HMAC-SHA1'),
            ('oauth_timestamp', 1285532322),
            ('oauth_version', 1.0),
            ('scope', "MyTradeMeRead,MyTradeMeWrite")]

print('POST&%(url)s&%(params)s' %  { 'url' : urllib.parse.quote_plus(url), 'params' : urllib.parse.quote_plus(urllib.parse.urlencode(params)) })

<强>输出

POST&https%3A%2F%2Fsecure.trademe.co.nz%2FOauth%2FRequestToken&oauth_callback%3Dhttp%253A%252F%252Fwww.website-tm-access.co.nz%252Ftrademe-callback%26oauth_consumer_key%3DC74CD73FDBE37D29BDD21BAB54BC70E422%26oauth_nonce%3D7O3kEe%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1285532322%26oauth_version%3D1.0%26scope%3DMyTradeMeRead%252CMyTradeMeWrite