我试图在提交之前urlencode这个字符串。
queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];
我试图在提交之前urlencode这个字符串。
queryString = 'eventName=' + evt.fields["eventName"] + '&' + 'eventDescription=' + evt.fields["eventDescription"];
当前回答
另一件可能还没有提到的事情是urllib.urlencode()将字典中的空值编码为字符串None,而不是将该形参作为不存在的参数。我不知道这是否是通常需要的,但不适合我的用例,因此我必须使用quote_plus。
其他回答
上下文
Python(版本2.7.2)
问题
您希望生成一个url编码的查询字符串。 您有一个包含名称-值对的字典或对象。 您希望能够控制名称-值对的输出顺序。
解决方案
urllib.urlencode urllib.quote_plus
陷阱
字典输出名称-值对的任意顺序 (请参见:为什么python对我的字典这样排序?) (请参见:为什么字典和集合中的顺序是任意的?) 处理不关心名称-值对顺序的情况 处理确实关心名称-值对顺序的情况 处理单个名称需要在所有名称-值对集中出现多次的情况
例子
以下是一个完整的解决方案,包括如何处理一些陷阱。
### ********************
## init python (version 2.7.2 )
import urllib
### ********************
## first setup a dictionary of name-value pairs
dict_name_value_pairs = {
"bravo" : "True != False",
"alpha" : "http://www.example.com",
"charlie" : "hello world",
"delta" : "1234567 !@#$%^&*",
"echo" : "user@example.com",
}
### ********************
## setup an exact ordering for the name-value pairs
ary_ordered_names = []
ary_ordered_names.append('alpha')
ary_ordered_names.append('bravo')
ary_ordered_names.append('charlie')
ary_ordered_names.append('delta')
ary_ordered_names.append('echo')
### ********************
## show the output results
if('NO we DO NOT care about the ordering of name-value pairs'):
queryString = urllib.urlencode(dict_name_value_pairs)
print queryString
"""
echo=user%40example.com&bravo=True+%21%3D+False&delta=1234567+%21%40%23%24%25%5E%26%2A&charlie=hello+world&alpha=http%3A%2F%2Fwww.example.com
"""
if('YES we DO care about the ordering of name-value pairs'):
queryString = "&".join( [ item+'='+urllib.quote_plus(dict_name_value_pairs[item]) for item in ary_ordered_names ] )
print queryString
"""
alpha=http%3A%2F%2Fwww.example.com&bravo=True+%21%3D+False&charlie=hello+world&delta=1234567+%21%40%23%24%25%5E%26%2A&echo=user%40example.com
"""
在Python 3中,这对我来说很有效
import urllib
urllib.parse.quote(query)
为了在需要同时支持python 2和3的脚本/程序中使用,six模块提供了quote和urlencode函数:
>>> from six.moves.urllib.parse import urlencode, quote
>>> data = {'some': 'query', 'for': 'encoding'}
>>> urlencode(data)
'some=query&for=encoding'
>>> url = '/some/url/with spaces and %;!<>&'
>>> quote(url)
'/some/url/with%20spaces%20and%20%25%3B%21%3C%3E%26'
Python 3:
urllib parse。引用+(字符串,安全= ",编码= no, errors= no)
注意urllib。Urlencode并不总是能做到这一点。问题在于,有些服务关心参数的顺序,而在创建字典时,这些顺序就会丢失。对于这种情况,使用urllib。正如Ricky建议的那样,quote_plus更好。