在Python请求中为字段使用各种输入文件

时间:2014-07-01 10:49:17

标签: python google-maps python-requests

我正在向Google的路线API发送查询。从另一个程序,我正在生成原点和目的地纬度和经度坐标。我目前正在将此文件保存在此结构的CSV文件中

Y,X,
51.516185371445459,-0.102373799765274,
51.512892732882598,-0.083154776597858,
51.514087813699639,-0.097131850779755,

我正在使用奇妙的python请求生成这些查询,但无法弄清楚如何在字段中指定,查看我创建的这些csv文件。我正在使用以下内容 -

>>> import json, requests
>>> params = {'origin': '*directory to csv location*', 'destination': '*directory to csv location*', 'key': '*key*'}
>>> r = requests.get('https://maps.googleapis.com/maps/api/directions/json', params=params)
>>> print(r.url)

如何告知请求文件的位置以及CSV中的哪些字段?对于API,需要输入坐标而不使用逗号或空格,因此我也需要执行此操作。

也许有比使用CSV更好的方法?

1 个答案:

答案 0 :(得分:2)

不,Google Maps API webservicerequests采用CSV文件名。您必须先从CSV文件中读取数据,然后将值传递给API。您可以使用csv module代替:

import requests
import csv

url = 'https://maps.googleapis.com/maps/api/directions/json'
apikey = '*key*'

with open('csv_filename', 'r', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    coords = ['{X},{Y}'.format(**row) for row in reader]
    start, waypoints, end = coords[0], coords[1:-1], coords[-1]
    params = {'origin': start,
              'waypoints': '|'.join(waypoints),
              'destination': end,
              'key': apikey}
    directions = requests.get(url, params=params).json()

此处,DictReader()将第一行作为键,因此每列可分别作为XY进行处理。然后我将这些格式化为Google可以理解的字符串。

我假设CSV文件代表了一系列获取路线的点数;开始,航点和结束。

演示:

>>> import csv
>>> import requests
>>> sample = '''\
... Y,X,
... 51.516185371445459,-0.102373799765274,
... 51.512892732882598,-0.083154776597858,
... 51.514087813699639,-0.097131850779755,
... '''
>>> reader = csv.DictReader(sample.splitlines())
>>> next(reader)
{'': '', 'X': '-0.102373799765274', 'Y': '51.516185371445459'}
>>> reader = csv.DictReader(sample.splitlines())
>>> coords = ['{X},{Y}'.format(**row) for row in reader]
>>> start, waypoints, end = coords[0], coords[1:-1], coords[-1]
>>> params = {'origin': start,
...           'waypoints': '|'.join(waypoints),
...           'destination': end,
...           'key': 'someapikey'}
>>> params
{'destination': '-0.097131850779755,51.514087813699639', 'waypoints': '-0.083154776597858,51.512892732882598', 'key': 'someapikey', 'origin': '-0.102373799765274,51.516185371445459'}
>>> url = 'https://maps.googleapis.com/maps/api/directions/json'
>>> directions = requests.get(url, params=params).json()
>>> from pprint import pprint
>>> pprint(directions)
{'routes': [], 'status': 'ZERO_RESULTS'}

在这种特定情况下,您的坐标实际上不会产生可行路线,因此会返回'status': 'ZERO_RESULTS'