2013-11-27 75 views
2

使用请求库如何创建一个多值int参数? 我试图给出一个原点到谷歌地图的API,但不能让它编码正确请求多值参数的url编码

start_coordinates = {'latitude':40.970321, 'longitude' :29.060873} 
end_coordinates = {'latitude':41.029967, 'longitude' :28.974656} 

start_latitude = start_coordinates.get('latitude') 
start_longitude = start_coordinates.get('longitude') 
end_latitude = end_coordinates.get('longitude') 
end_longitude = end_coordinates.get('latitude') 

url = 'http://maps.googleapis.com/maps/api/directions/json' 
params = { 
    'origin' : '%s,%s' %(start_latitude,start_longitude), 
    'destination' : '%s,%s' %(end_latitude, end_longitude), 
    'sensor' : 'false', 
    } 
google_response = requests.get(url,params=params) 

google_response是:

u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321%2C29.060873&destination=28.974656%2C41.029967&sensor=false'

,但它应该是:

u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=28.974656,41.029967&sensor=false'

其中的参数应该像origin=40.970321,29.060873而不是destination=28.974656%2C41.029967

另一个例子:

这并不工作: http://maps.googleapis.com/maps/api/directions/json?origin=40.970321%2C29.060873&destination=28.974656%2C41.029967&sensor=false

这个工程: http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=41.029967,28.974656&sensor=false


它显然是在我的部分错误似乎:

well this is embarrassing. It was my first few lines that threw the code off, it should be: 

start_coordinates = {'latitude':40.970321, 'longitude' :29.060873} 
end_coordinates = {'latitude':41.029967, 'longitude' :28.974656} 
start_latitude = start_coordinates.get('latitude') 
start_longitude = start_coordinates.get('longitude') 
end_latitude = end_coordinates.get('latitude') 
end_longitude = end_coordinates.get('longitude') 


url = 'http://maps.googleapis.com/maps/api/directions/json' 
params = { 
    'origin' : '%s,%s' %(start_latitude,start_longitude), 
    'destination' : '%s,%s' %(end_latitude, end_longitude), 
    'sensor' : 'false', 
    } 
google_response = requests.get(url, params=params) 

我得到了end_longitudeend_latitude错误。因此,这修复它

+1

为什么不能编码逗号? –

+0

尝试提供可复制的示例(即设置变量,如start_latitude等) – dorvak

+0

@dorvak添加了可复制的示例。 @MartijnPieters它被编码,但编码的%2C不被谷歌接受。当状态为 – Salyangoz

回答

1

如果你坚持一个decodec网址,试试这个:

In [54]: urllib.unquote(google_response.url).decode('utf8') 
Out[54]: u'http://maps.googleapis.com/maps/api/directions/json?origin=40.970321,29.060873&destination=28.974656,41.029967&sensor=false' 

编辑:由于urllib的改变排序(我认为这是由于使用的字典内),这种方法没有按”不管工作。我建议手动构建网址,通过pythons字符串连接/格式化方法。

+0

它因为内部命令排序。谢谢 – Salyangoz

+0

确实。在这种情况下,我倾向于使用OrderedDict(或者列表或元组)。 – dorvak