2013-11-27 3 views
2

Использование библиотеки запросов, как я могу сделать многозначный параметр int? Я пытаюсь дать начало координат в API Карт Google, но не могу получить его, чтобы кодировать правильнозапрашивает кодировку 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_longitude и end_latitude неправильно. Так что это фиксирует это

+1

Почему запятая не может быть закодирована? –

+0

Попробуйте предоставить воспроизводимый пример (например, установите переменные, такие как start_latitude и т. Д.). – dorvak

+0

@dorvak добавил реплицируемый пример. @MartijnPieters Его кодируют, но закодированный% 2C не принимается из Google. Я получаю «ZERO_RESULTS» ​​'для статуса – Salyangoz

ответ

1

Если вы настаиваете на decodec URL, попробуйте это:

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' 

EDIT: Как URLLIB изменяет порядок (я думаю, что это связано с использованием Dict внутренне), этот метод Безразлично» т. Я бы предложил построить url вручную, используя методы python string-concatenation/formating.

+0

его из-за внутреннего заказа dicts. Спасибо – Salyangoz

+0

Действительно. В этом случае я обычно использую OrderedDict (или списки или кортежи). – dorvak

Смежные вопросы