forked from codeforamerica/srtracker
/
app.py
214 lines (171 loc) · 7.97 KB
/
app.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
209
210
211
212
213
214
import os
from flask import Flask, render_template, request, abort, redirect, url_for, make_response, session
import requests
import iso8601
import updater
import logging
fileHandler = logging.FileHandler('application2.log')
logger = logging.getLogger('TESTHARNESSFILE')
logger.addHandler(fileHandler)
logger.setLevel(logging.DEBUG)
import pprint
pp = pprint.PrettyPrinter(indent=4)
import types
# Config
DEBUG = True
OPEN311_SERVER = 'http://localhost:5000'
OPEN311_API_KEY = ''
PASSWORD_PROTECTED = False
SECRET_KEY = 'please_please_change_this!'
app = Flask(__name__)
@app.before_request
def password_protect():
if app.config['PASSWORD_PROTECTED']:
auth = request.authorization
if not auth or auth.password != app.config['PASSWORD']:
# Tell the browser to do basic auth
return make_response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def debugrequest (r):
logger.debug("Request form %s" % pp.pformat(r.form))
logger.debug("Request args %s" % pp.pformat(r.args))
logger.debug("Request values %s" % pp.pformat(r.values))
logger.debug("Request data %s" % pp.pformat(r.data))
logger.debug("Request url %s" % pp.pformat(r.url))
logger.debug("Request headers %s" % pp.pformat(r.headers))
logger.debug("Request env %s" % pp.pformat(r.environ))
# r.cookies
# r.stream
# r.files
# r.method
# r.path
# r.script_root
# r.base_url
# r.url_root
def debugresponse (r) :
logger.debug("Response %s" % pp.pformat(r))
logger.debug("Response Header %s" % pp.pformat(r.headers))
logger.debug("Response Status code %s" % pp.pformat(r.status_code))
logger.debug("Response content %s" % pp.pformat(r.content))
@app.route("/")
def index():
url = '%s/requests.json' % app.config['OPEN311_SERVER']
params = {'extensions': 'true', 'legacy': 'false'}
if app.config['OPEN311_API_KEY']:
params['api_key'] = app.config['OPEN311_API_KEY']
logger.debug("Server: %s" % app.config['OPEN311_SERVER'])
logger.debug("Going to request url %s" % pp.pformat(url))
logger.debug("going to request with params: %s" % pp.pformat(params))
r = requests.get(url, params=params)
if 'request_id' in request.args:
request_id =request.args['request_id']
else :
request_id ="unknown"
try :
service_requests=r.json
logger.debug("service_requests %s" % pp.pformat(service_requests))
except :
logger.error("There was an error in the 311 service request response")
debugresponse (r)
debugrequest (request)
return ("There was an error in the 311 service request response", 500, None)
if r.status_code != 200:
# TODO: need a template
logger.error("There was an error getting service request data for request id : %s ." % request_id)
debugresponse (r)
debugrequest (request)
return ("There was an error getting service request data for request id : %s ." % request_id, 500, None)
return render_template('index.html', sr=service_requests)
@app.route("/requests")
def redirect_request():
if 'request_id' in request.args:
request_id =request.args['request_id']
return redirect(url_for('show_request', request_id=request_id))
else:
abort(404)
@app.route("/requests/<request_id>")
def show_request(request_id):
request_id = request_id.lstrip('#')
# TODO: Should probably use Three or something nice for this...
url = '%s/requests/%s.json' % (app.config['OPEN311_SERVER'], request_id)
params = {'extensions': 'true', 'legacy': 'false'}
if app.config['OPEN311_API_KEY']:
params['api_key'] = app.config['OPEN311_API_KEY']
r = requests.get(url, params=params)
if r.status_code == 404:
# TODO: need a template
# logger.error("There is no service request on file for #%s" % request_id)
# debugresponse (r)
# debugrequest (request)
return render_template('no_service_request_found.html', rid=request_id)
elif r.status_code != 200:
# TODO: need a template
logger.error("There was an error getting data about service request #%s" % request_id)
debugresponse (r)
debugrequest (request)
return ("There was an error getting data about service request #%s" % request_id, 404, None)
srs = r.json
if srs:
# debug the data
logger.debug("got data %s" % pp.pformat(srs))
# check the return data, it should be a list
if (not isinstance(srs, types.ListType)):
return ("There was an error getting data about service request #%s" % request_id, 404, None)
sr = srs[0]
sr['requested_datetime'] = iso8601.parse_date(sr['requested_datetime'])
for note in sr['notes']:
note['datetime'] = iso8601.parse_date(note['datetime'])
# add follow-on closure data
by_id = {}
for note in sr['notes']:
if(note['extended_attributes']['closed_datetime']):
note['extended_attributes']['closed_datetime']= iso8601.parse_date( note['extended_attributes']['closed_datetime'] )
if note['type'] == 'follow_on':
note_sr_id = note['extended_attributes']['service_request_id']
if note_sr_id in by_id:
if note['description'].endswith('Closed'):
original = by_id[note_sr_id]
original['extended_attributes']['closed_datetime'] = note['datetime']
else:
by_id[note_sr_id] = note
sr['notes'].reverse()
subscribed = False
if sr['status'] == 'open' and session.get('email', None):
# TODO: when subscription service supports more than e-mail,
# we should probably be able to show all your subscriptions here
subscribed = updater.subscription_exists(request_id, 'email', session.get('email', ''))
#more checks that should not be in the template, but in the app. lets have some type of logical separation here.
assert(sr['address'])
assert isinstance(sr['address'], types.StringTypes)
assert(sr['service_name'])
assert(sr['description'])
assert(sr['status'])
assert(sr['extended_attributes'])
assert(sr['extended_attributes']['channel'])
assert(sr['agency_responsible'])
assert(sr['service_request_id'])
body = render_template('service_request.html', sr=sr, subscribed=subscribed)
return (body, 200, None)
else:
return render_template('no_service_request_found.html', rid=request_id)
@app.route("/subscribe/<request_id>", methods=["POST"])
def subscribe(request_id):
email = request.form.get('update_email')
# TODO: validate email
if email:
updater.subscribe(request_id, 'email', email)
# TODO: should we get back a secret subscription key and use that instead?
session['email'] = email
return redirect(url_for('show_request', request_id=request_id))
if __name__ == "__main__":
app.config.from_object(__name__)
app.debug = os.environ.get('DEBUG', str(app.debug)) == 'True'
app.secret_key = os.environ.get('SECRET_KEY', app.secret_key)
app.config['OPEN311_SERVER'] = os.environ.get('OPEN311_SERVER', OPEN311_SERVER)
app.config['OPEN311_API_KEY'] = os.environ.get('OPEN311_API_KEY', OPEN311_API_KEY)
app.config['PASSWORD_PROTECTED'] = os.environ.get('PASSWORD_PROTECTED', str(PASSWORD_PROTECTED)) == 'True'
app.config['PASSWORD'] = os.environ.get('PASSWORD', '')
port = int(os.environ.get('PORT', 5100))
app.run(host='0.0.0.0', port=port)