如何在谷歌应用引擎中编码我的URL参数?
我在用Python做地理编码,我觉得我需要用urllencode来编码变量region
,这样才能处理包含空格和其他特殊字符的内容:
url = urllib.urlencode('http://maps.googleapis.com/maps/api/geocode/json?address='+region+'&sensor=false')
logging.info('url:'+url)
result = urlfetch.fetch(url)
当变量region包含空格时,会生成一个错误日志。
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~montaoproject/pricehandling.355268396595012751/in.py", line 153, in get
url = urllib.urlencode('http://maps.googleapis.com/maps/api/geocode/json?address='+region+'&sensor=false')
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib.py", line 1275, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object
背景是我之前问过的另一个问题,我遇到的问题是代码可以正常工作,但对于包含两个或更多单词的区域,比如带有空格的名称,就不行。
https://stackoverflow.com/questions/8441063/how-should-i-use-urlfetch-here
在生产环境中,我用了另一个变量。我以为空格没关系。当我尝试不包含空格的变量时,它就能正常工作。所以你能告诉我应该如何编码这个url变量,以便它能接受空格和其他“特殊”字符吗?
谢谢你
2 个回答
1
使用 urllib.pathname2url,这个方法可以直接处理一个字符串,不需要用字典。
6
只需要对你的查询字符串部分进行编码
比如:
param = {"address" : region,
"sensor" : "false"
}
或者
param = [("address", region), ("sensor", "false")]
然后
encoded_param = urllib.urlencode(param)
url = 'http://maps.googleapis.com/maps/api/geocode/json'
url = url + '?' + encoded_param
result = urlfetch.fetch(url)