forked from data-for-change/anyway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
208 lines (175 loc) · 7.08 KB
/
main.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
import os
import logging
import urllib
import csv
from StringIO import StringIO
import datetime
import time
import jinja2
from flask import make_response, jsonify, render_template
import flask.ext.assets
from webassets.ext.jinja2 import AssetsExtension
from webassets import Environment as AssetsEnvironment
from database import db_session
from models import *
from base import *
import utilities
app = utilities.init_flask(__name__)
assets = flask.ext.assets.Environment()
assets.init_app(app)
assets_env = AssetsEnvironment('./static/', '/static')
jinja_environment = jinja2.Environment(
autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")),
extensions=[AssetsExtension])
jinja_environment.assets_environment = assets_env
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
@app.route("/markers")
@user_optional
def markers(methods=["GET", "POST"]):
logging.debug('getting markers')
if request.method == "GET":
ne_lat = float(request.values['ne_lat'])
ne_lng = float(request.values['ne_lng'])
sw_lat = float(request.values['sw_lat'])
sw_lng = float(request.values['sw_lng'])
zoom = int(request.values['zoom'])
start_date = datetime.date.fromtimestamp(int(request.values['start_date']))
end_date = datetime.date.fromtimestamp(int(request.values['end_date']))
logging.debug('start: %s, end: %s' % (start_date, end_date))
min_zoom_level = 16
if zoom < min_zoom_level:
markers = []
else:
# query = Marker.all()
# if 'start_time' in request.values:
# query = query.filter("created >=", request.values["start_time"])
# if 'start_time' in request.values:
# query = query.filter("created <=", request.values["end_time"])
print ""
logging.debug('querying markers in bounding box')
results = Marker.bounding_box_fetch(ne_lat, ne_lng, sw_lat, sw_lng,
start_date, end_date)
logging.debug('serializing markers')
markers = [marker.serialize() for marker in results.all()]
if request.values.get('format') == 'csv':
if not markers:
raise Exception("No markers available.")
output_file = StringIO()
output = csv.DictWriter(output_file, markers[0].keys())
output.writeheader()
for marker in markers:
row = {k: v.encode('utf8')
if type(v) is unicode else v
for k, v in marker.iteritems()}
output.writerow(row)
return make_response((output_file.getvalue(),
200,
{u'Content-Type': 'text/csv',
u'Content-Disposition': u'attachment; filename="data.csv"'}))
else: # defaults to json
return jsonify(markers=markers)
else:
data = json.loads(self.request.body)
marker = Marker.parse(data)
marker.user = self.user
marker.update_location()
marker.put()
return make_response(json.dumps(marker.serialize(self.user)))
@app.route("/markers/(.*)", methods=["GET", "PUT", "DELETE"])
@user_required
def marker(self, key_name):
if request.method == "GET":
marker = Marker.get_by_key_name(key_name)
return make_response(json.dumps(marker.serialize(self.user)))
elif request.method == "PUT":
marker = Marker.get_by_key_name(key_name)
data = json.loads(self.request.body)
marker.update(data, self.user)
return make_response(json.dumps(marker.serialize(self.user)))
elif request.method == "DELETE":
marker = Marker.get_by_key_name(key_name)
marker.delete()
@app.route("/login", methods=["POST"])
@user_optional
def login():
user = get_user()
if user:
return make_response(json.dumps(user.serialize()))
if request.json:
facebook_data = request.json
user_id = facebook_data["userID"]
access_token = facebook_data["accessToken"]
user_details = json.loads(urllib.urlopen("https://graph.facebook.com/me?access_token=" + access_token).read())
# login successful
if user_details["id"] == user_id:
user = User.query.filter(User.email == user_details["email"]).scalar()
if not user:
user = User(
email = user_details["email"],
first_name = user_details["first_name"],
last_name = user_details["last_name"],
username = user_details["username"],
facebook_id = user_details["id"],
facebook_url = user_details["link"],
access_token = facebook_data["accessToken"]
)
else:
user.access_token = facebook_data["accessToken"]
db_session.add(user)
set_user(user)
return make_response(json.dumps(user.serialize()))
else:
raise Exception("Error in logging in.")
else:
raise Exception("No login data or user logged in.")
@app.route("/logout")
@user_required
def do_logout():
logout()
@app.route("/follow/(.*)")
@user_required
def follow(key_name):
marker = Marker.get_by_key_name(key_name)
follower = Follower.all().filter("marker", marker).filter("user", self.user).get()
if not follower:
Follower(parent = marker, marker = marker, user = self.user).put()
@app.route("/unfollow/(.*)")
@user_required
def unfollow(key_name):
marker = Marker.get_by_key_name(key_name)
follower = Follower.all().filter("marker", marker).filter("user", self.user).get()
if follower:
follower.delete()
@app.route('/', defaults={'marker_id': None})
@app.route('/<int:marker_id>')
def main(marker_id):
# at this point the marker id is just a running number, and the
# LMS is in the description and needs to be promoted to a DB
# field so we can query it. We also need to add a provider id.
context = {}
marker = None
if 'marker' in request.values:
markers = Marker.get_marker(request.values['marker'])
if markers.count() == 1:
marker = markers[0]
context['coordinates'] = (marker.latitude, marker.longitude)
context['marker'] = marker.id
if 'start_date' in request.values:
context['start_date'] = string2timestamp(request.values['start_date'])
elif marker:
context['start_date'] = year2timestamp(marker.created.year)
if 'end_date' in request.values:
context['end_date'] = string2timestamp(request.values['end_date'])
elif marker:
context['end_date'] = year2timestamp(marker.created.year + 1)
return render_template('index.html', **context)
def string2timestamp(s):
return time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
def year2timestamp(y):
return time.mktime(datetime.date(y, 1, 1).timetuple())
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
app.run(debug=True)