-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathrunkeeper_demo.py
208 lines (176 loc) · 7.39 KB
/
runkeeper_demo.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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python
"""Demo Application for HealthGraph-API Python Library developed using Bottle
fast, simple and lightweight WSGI micro web-framework for Python.
The configuration file runkeeper_demo.conf must be edited to set the client_id
and client_secret. The client_id and client_secret is generated upon registration
in the Applications Portal of Health Graph (http://runkeeper.com/partner).
Running the demo: python runkeeper_demo.py
Point the web browser to the following URL: http://127.0.0.1:8000
"""
import sys
import os
import optparse
import ConfigParser
import bottle
import healthgraph
from beaker.middleware import SessionMiddleware
__author__ = "Ali Onur Uyar"
__copyright__ = "Copyright 2012, Ali Onur Uyar"
__credits__ = []
__license__ = "GPL"
__version__ = "0.3.0"
__maintainer__ = "Ali Onur Uyar"
__email__ = "aouyar at gmail.com"
__status__ = "Development"
# Defaults
conf = {'baseurl': 'http://127.0.0.1:8000',
'bindaddr': '127.0.0.1',
'bindport': 8000,
}
defaultConfFilename = 'runkeeper_demo.conf'
# Session Options
sessionOpts = {
'session.type': 'file',
'session.cookie_expires': 1800,
'session.data_dir': '/tmp/cache/data',
'session.lock_dir': '/tmp/cache/data',
'session.auto': False,
}
class ConfigurationError(Exception):
"""Base classs for Configuration Errors"""
pass
@bottle.route('/')
def index():
sess = bottle.request.environ['beaker.session']
if sess.has_key('rk_access_token'):
bottle.redirect('/welcome')
else:
rk_auth_mgr = healthgraph.AuthManager(conf['client_id'], conf['client_secret'],
'/'.join((conf['baseurl'], 'login',)))
rk_auth_uri = rk_auth_mgr.get_login_url()
rk_button_img = rk_auth_mgr.get_login_button_url('blue', 'black', 300)
return bottle.template('index.html', {'rk_button_img': rk_button_img,
'rk_auth_uri': rk_auth_uri,})
@bottle.route('/login')
def login():
sess = bottle.request.environ['beaker.session']
code = bottle.request.query.get('code')
if code is not None:
rk_auth_mgr = healthgraph.AuthManager(conf['client_id'], conf['client_secret'],
'/'.join((conf['baseurl'], 'login',)))
access_token = rk_auth_mgr.get_access_token(code)
sess['rk_access_token'] = access_token
sess.save()
bottle.redirect('/welcome')
@bottle.route('/welcome')
def welcome():
sess = bottle.request.environ['beaker.session']
access_token = sess.get('rk_access_token')
if access_token is not None:
user = healthgraph.User(session=healthgraph.Session(access_token))
profile = user.get_profile()
records = user.get_records()
act_iter = user.get_fitness_activity_iter()
activities = [act_iter.next() for _ in range(5)]
return bottle.template('welcome.html',
profile=profile,
activities=activities,
records=records.get_totals())
else:
bottle.redirect('/')
@bottle.route('/logout')
def logout():
sess = bottle.request.environ['beaker.session']
sess.delete()
bottle.redirect('/')
@bottle.route('/view_access_token')
def view_access_token():
sess = bottle.request.environ['beaker.session']
access_token = sess.get('rk_access_token')
if access_token is not None:
remote_addr = bottle.request.get('REMOTE_ADDR')
return bottle.template('access_token.html',
remote_addr=remote_addr,
access_token=(access_token
if remote_addr == '127.0.0.1'
else None))
else:
bottle.redirect('/')
def parse_cmdline(argv=None):
"""Parse command line options.
@param argv: List of command line arguments. If None, get list from system.
@return: Tuple of Option List and Argument List.
"""
parser = optparse.OptionParser()
parser.add_option('-c', '--conf', help='Configuration file path.',
dest='confpath',default=None)
parser.add_option('-p', '--bindport',
help='Bind to TCP Port. (Default: %d)' % conf['bindport'],
dest='bindport', type='int', default=None, action='store')
parser.add_option('-b', '--bindaddr',
help='Bind to IP Address. (Default: %s)' % conf['bindaddr'],
dest='bindaddr', default=None, action='store')
parser.add_option('-u', '--baseurl',
help='Base URL. (Default: %s)' % conf['baseurl'],
dest='baseurl', default=None, action='store')
parser.add_option('-D', '--devel', help='Enable development mode.',
dest='devel', default=False, action='store_true')
if argv is None:
return parser.parse_args()
else:
return parser.parse_args(argv[1:])
def parse_conf_files(conf_paths):
"""Parse the configuration file and return dictionary of configuration
options.
@param conf_paths: List of configuration file paths to parse.
@return: Dictionary of configuration options.
"""
conf_file = ConfigParser.RawConfigParser()
conf_read = conf_file.read(conf_paths)
conf = {}
try:
if conf_read:
conf['client_id'] = conf_file.get('runkeeper', 'client_id')
conf['client_secret'] = conf_file.get('runkeeper', 'client_secret')
if conf_file.has_option('runkeeper', 'bindport'):
conf['bindport'] = conf_file.getint('runkeeper', 'bindport')
if conf_file.has_option('runkeeper', 'bindaddr'):
conf['bindaddr'] = conf_file.get('runkeeper', 'bindaddr')
if conf_file.has_option('runkeeper', 'baseurl'):
conf['baseurl'] = conf_file.get('runkeeper', 'baseurl')
return conf
except ConfigParser.Error:
raise ConfigurationError("Error parsing configuration file(s): %s\n"
% sys.exc_info()[1])
else:
raise ConfigurationError("No valid configuration file (%s) found."
% defaultConfFilename)
def main(argv=None):
"""Main Block - Configure and run the Bottle Web Server."""
cmd_opts = parse_cmdline(argv)[0]
if cmd_opts.confpath is not None:
if os.path.exists(cmd_opts.confpath):
conf_paths = [cmd_opts.confpath,]
else:
return "Configuration file not found: %s" % cmd_opts.confpath
else:
conf_paths = [os.path.join(path, defaultConfFilename)
for path in ('/etc', '.',)]
try:
conf.update(parse_conf_files(conf_paths))
except ConfigurationError:
return(sys.exc_info()[1])
if cmd_opts.bindport is not None:
conf['bindport'] = cmd_opts.bindport
if cmd_opts.bindaddr is not None:
conf['bindaddr'] = cmd_opts.bindaddr
if cmd_opts.baseurl is not None:
conf['baseurl'] = cmd_opts.baseurl
if cmd_opts.devel:
from bottle import debug
debug(True)
app = SessionMiddleware(bottle.app(), sessionOpts)
bottle.run(app=app, host=conf['bindaddr'], port=conf['bindport'],
reloader=cmd_opts.devel)
if __name__ == "__main__":
sys.exit(main())