如何使用urllib编码url


How to encode url using urllib

我有这个php函数,我在python 2.7中开发相同的:

//PHP
$actionSLK = 'https://test.monsite.com/script.cgi';
$storeId = 'test';
$cartId = 'test2';
$totalAmountTx = '100';
$email = 'test@monsite.com';
$SLKSecretKey = 'secret';
$dataMD5=$actionSLK . $storeId . $cartId . $totalAmountTx . $email . $SLKSecretKey
$checksum=MD5(utf8entities(rawurlencode($dataMD5)));
#PYTHON:
from hashlib import md5
import urllib
actionSLK = 'https://test.monsite.com/script.cgi'
storeId = 'test'
cartId = 'test2'
totalAmountTx = '100'
email = 'test@monsite.com'
SLKSecretKey = 'secret'
dataMD5 = actionSLK + storeId + cartId + totalAmountTx + email + SLKSecretKey
checksum = md5(urllib.quote(dataMD5).encode('utf8')).hexdigest()

我发现的问题是计算的校验和不相同的MD5,然后我检查了编码的url(生成的一个:'https://test.monsite.com/script.cgitesttest100test@monsite.comsecret'),这里我们是:

//PHP
$checksum=MD5('https%3A%2F%2Ftest.monsite.com%2Fscript.cgitesttest100test%40monsite.comsecret');
#PYTHON
checksum = md5('https%3A//test.monsite.com/script.cgitesttest100test%40monsite.comsecret').hexdigest()

所以斜杠没有被编码,所以当生成不同的校验和时会发生错误。

在urllib中是否有其他函数可以对url进行详细编码?

urllib.quote()通常用于编码包括路径在内的url部分,因此,默认情况下,/被认为是一个安全字符。显式传递safe='':

>>> dataMD5
'https://test.monsite.com/script.cgitesttest2100test@monsite.comsecret'
>>> import urllib
>>> urllib.quote(dataMD5)
'https%3A//test.monsite.com/script.cgitesttest2100test%40monsite.comsecret'
>>> urllib.quote(dataMD5, safe='')
'https%3A%2F%2Ftest.monsite.com%2Fscript.cgitesttest2100test%40monsite.comsecret'

quote_plus()通常用于创建application/x-www-form-urlencoded数据,因此默认为safe=''

要确定应该使用quote_plus()还是quote(),请考虑带有空格的数据:

>>> urllib.quote_plus('/ /')
'%2F+%2F'
>>> urllib.quote('/ /', safe='')
'%2F%20%2F'

PHP的rawurlencode()产生后者,因此您应该使用quote(safe='')而不是quote_plus()

您可以使用urllib.quote_plus():

>>> encoded = urllib.quote_plus("https://test.monsite.com/script.cgitesttest100test@monsite.comsecret")
>>> encoded
'https%3A%2F%2Ftest.monsite.com%2Fscript.cgitesttest100test%40monsite.comsecret'

使用urllib.quote_plus您可以实现它

actionSLK = "https://test.monsite.com/script.cgi"
urllib.quote_plus(actionSLK)
>>https%3A%2F%2Ftest.monsite.com%2Fscript.cgi