-
Notifications
You must be signed in to change notification settings - Fork 3
/
createCache.py
41 lines (34 loc) · 1.17 KB
/
createCache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
import requests
import pickle
import maputils
API_KEY = maputils.config['api_keys']['google_distance_matrix']
BASE_URL = 'https://maps.googleapis.com/maps/api/distancematrix'
CAPITALS = maputils.CAPITALS
# cachedDistDur = pickle.load(open('cache.p', 'rb'))
cachedDistDur = {}
def getDistDur(origin, destination):
# print origin, destination
key = tuple(sorted([origin, destination]))
if key in cachedDistDur:
# print origin, destination, 'from cache'
return cachedDistDur[key]
origin = origin.replace(' ','+')
destination = destination.replace(' ','+')
r = requests.get(BASE_URL + '/json?units=imperial&origins=' + origin + '&destinations=' + destination + '&key=' + API_KEY)
if r.json()['status'] == 'OK':
dist = r.json()['rows'][0]['elements'][0]['distance']['value']
time = r.json()['rows'][0]['elements'][0]['duration']['value']
result = (dist, time)
cachedDistDur[key] = result
print key, result
# print origin, destination, result
return result
else:
raise Exception('Over api limit!')
for p1 in CAPITALS[:50]:
print p1
for p2 in CAPITALS[:50]:
if p1 != p2:
getDistDur(p1, p2)
pickle.dump(cachedDistDur, open('cache.p', 'wb'), -1)