-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathrider_dashboard.py
More file actions
92 lines (71 loc) · 2.65 KB
/
rider_dashboard.py
File metadata and controls
92 lines (71 loc) · 2.65 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from flask import Flask, redirect, request, render_template
from example import utils # NOQA
from example.utils import import_app_credentials
from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.client import UberRidesClient
from collections import OrderedDict, Counter
app = Flask(__name__, template_folder="./")
credentials = import_app_credentials('config.rider.yaml')
auth_flow = AuthorizationCodeGrant(
credentials.get('client_id'),
credentials.get('scopes'),
credentials.get('client_secret'),
credentials.get('redirect_url'),
)
@app.route('/')
def index():
"""Index controller to redirect user to sign in with uber."""
return redirect(auth_flow.get_authorization_url())
@app.route('/uber/connect')
def connect():
"""Connect controller to handle token exchange and query Uber API."""
# Exchange authorization code for acceess token and create session
session = auth_flow.get_session(request.url)
client = UberRidesClient(session)
# Fetch profile for rider
profile = client.get_rider_profile().json
# Fetch all trips from history endpoint
trips = []
i = 0
while True:
try:
response = client.get_rider_trips(
limit=50,
offset=i)
i += 50
if len(response.json['history']) > 0:
trips += response.json['history']
else:
break
except:
break
pass
# Compute trip stats for # of rides and distance
total_rides = 0
total_distance_traveled = 0
# Compute ranked list of # trips per city
cities = list()
for ride in trips:
cities.append(ride['start_city']['display_name'])
# only parse actually completed trips
if ride['distance'] > 0:
total_rides += 1
total_distance_traveled += int(ride['distance'])
total_cities = 0
locations_counter = Counter(cities)
locations = OrderedDict()
cities_by_frequency = sorted(cities, key=lambda x: -locations_counter[x])
for city in list(cities_by_frequency):
if city not in locations:
total_cities += 1
locations[city] = cities.count(city)
return render_template('rider_dashboard.html',
profile=profile,
trips=trips,
locations=locations,
total_rides=total_rides,
total_cities=total_cities,
total_distance_traveled=total_distance_traveled
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)