/
leaderboard.py
380 lines (303 loc) · 9.35 KB
/
leaderboard.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Leaderboard Service
~~~~~~~~~~~~~~~~~~~
A service that will return the statistics on which objects are the most liked
in our community.
The service provides APIs for Like and unlike.
Most importantly the service provides an API for that will provide a means of querying
for ranked list of the top K
images that have received the most likes in the following time periods:
last 24 hours, => day
36 hours, => 3rd day
1 week, => week
1 month, => month
1 year.=> year.
Base URL:
http://imageleaderboard.herokuapp.com/api/images/
API:
Like:
Unlike:
Leaderboard:
leaderboard?period=24hrs&k=10
API Expects:
returns:
200 - successful submission
400 - Bad request
500 - Server error
:copyright: (c) 2014 by Gustavo Sandoval.
"""
import os
import pymongo
from flask import Flask, request, session, g, abort, make_response, Response, json, jsonify
from urlparse import urlparse
import datetime
from datetime import timedelta
# the main app.
# comment or uncomment the debug = true for getting debug logging
# while running on local host of the unit tests.
app = Flask(__name__)
#app.debug = True
###############################################################
#
# Database stuff
#
###############################################################
##
## Opens a new db connection if there's none for the current app context
##
def get_db():
#app.logger.debug('Entered: get_db' )
if not hasattr(g, 'mongo_db'):
g.mongo_db = init_db()
return g.mongo_db
##
## Connects to the actual db
## First tries the one in heroku then localhost
def init_db():
#app.logger.debug('Entered: init_db' )
mongo_url = os.environ.get('MONGOHQ_URL')
if mongo_url:
conn = pymongo.Connection(mongo_url)
# app.logger.debug('got heroku connection to mongo' )
db = conn[urlparse(mongo_url).path[1:]]
else:
conn = pymongo.Connection('localhost', 27017)
# app.logger.debug('got localhost connection to mongo' )
db = conn['leaderboard-db4']
return db
###############################################################
#
# Routes
#
###############################################################
###
### Create or liking an Image:
### Supports: POST
### Expects: json with image and user.
### Returns: image_id and count. HTTP 200 or 400
###
### Format for call: api/images/like
### body: {image:'imageid', user:'userid'}
###
### Using Curl:
### curl -d '{"user":"123", "image":"123"}' http://imageleaderboard.herokuapp.com/api/images/like --header "Content-Type:application/json"
###
@app.route("/api/images/like", methods=['POST'])
def images_like():
app.logger.debug('Entered images_like. Payload: ' )
json = request.get_json()
app.logger.debug("json:")
app.logger.debug(json)
# First validate all the payload & params
if (json == None):
return Response(status=400, response='invalid payload')
image = json.get('image')
if (image == None):
return Response(status=400, response='invalid image id')
user = json.get('user')
if (user == None):
return Response(status=400, response='invalid user id')
#everything ok, let's do work
db = get_db()
likes = db['likes']
count = 1
# check to see if this exists in the db and how many likes it has
key = likes.find_one( { "image_id" : image} )
if (key is None):
# first time seen
app.logger.debug('inserting new entry in db' )
like = {
'image_id' : image,
'user_id' : user,
'date_list' : [datetime.datetime.utcnow()],
'count' : count
}
# since first time seen, we insert in the db
like_id = likes.insert(like)
app.logger.debug('inserted in db' )
else:
# we have seen this image id before
app.logger.debug('updating in db' )
app.logger.debug(key)
count = key['count']
count = count + 1
# add at the end of the list of dates
datelist = key['date_list']
datelist.append(datetime.datetime.utcnow())
# update the entry in the db
like_id = likes.update(
{ 'image_id' : image, },
{
'image_id' : image,
'user_id' : user,
'date_list' : datelist,
'count' : count
},
)
app.logger.debug('updated in db' )
resp = jsonify(image_id=image, image_count=count)
return resp
###
### Unliking an Image
### Supports: POST
### Expects: json with image and user.
### Returns: image_id and count. HTTP 200, 400 or 304 if not found
###
### Format for call: api/images/unlike
### body: {image:'imageid', user:'userid'}
###
### Where:
### - period must be one of: '24hrs', '36hrs', 'week', 'month', 'year'
### - k must be between 0 and 100
###
### ### Using Curl:
### curl -d '{"user":"123", "image":"123"}' http://imageleaderboard.herokuapp.com/api/images/unlike --header "Content-Type:application/json"
###
@app.route("/api/images/unlike", methods=['POST'])
def images_unlike():
app.logger.debug('Entered images_unlike. Payload: ' )
json = request.get_json()
app.logger.debug("json:")
app.logger.debug(json)
# First validate all the payload & params
if (json == None):
return Response(status=400, response='invalid payload')
image = json.get('image')
if (image == None):
return Response(status=400, response='invalid image id')
user = request.get_json().get('user')
if (user == None):
return Response(status=400, response='invalid user id')
#everything ok, let's do work
db = get_db()
likes = db['likes']
# check to see if this exists in the db if it doesn't
# we will return HTTP 304 not modified
key = likes.find_one( { "image_id" : image} )
if (key is None):
error = 'not modified'
return Response(status=304, response=error)
count = key['count']
count = count - 1
if (count == 0):
# we need to remove the entry for the image
app.logger.debug('removing entry for ' + str(image) )
likes.remove({'image_id' : image})
else:
# we just need to decrease the likes
app.logger.debug('decreasing the likes for ' + str(image))
#remove the last date
datelist = key['date_list']
datelist.pop()
# update in the db
like_id = likes.update(
{ 'image_id' : image, },
{
'image_id' : image,
'user_id' : user,
'date_list' : datelist,
'count' : count
},
)
app.logger.debug('updated in db' )
resp = jsonify(image_id=image, image_count=count)
return resp
###
### Route for getting the leaderboard or statistics for images
### The API should provide a means of querying for ranked list of the top
### K images that have received the most likes in the following time periods:
### last 24 hours, 36 hours, 1 week, 1 month, and 1 year.
###
### Format for call: api/images/leaderboard?period=year&k=10'
###
### Where:
### - period must be one of: '24hrs', '36hrs', 'week', 'month', 'year'
### - k must be between 0 and 100
###
### response:
# {
# "likes": [
# {
# "image_id": "12",
# "count" : 100
# },
# {
# "image_id": "1234",
# "count" : 12
# }
# ]
# }
@app.route("/api/images/leaderboard", methods=['GET'])
def images_leaderboard():
app.logger.debug('Entered images_leaderboard. Payload: ' )
args = request.args.to_dict()
app.logger.debug(args)
# First validate all the payload & params
if (len(args) == 0):
return Response(status=400, response='invalid payload')
period = args.get('period', '')
if (period == None or period not in ['24hrs', '36hrs', 'week', 'month', 'year']):
return Response(status=400, response='invalid period. Valid are 24hrs, 36hrs, week, month, year')
k = args.get('k', '')
try:
n = int(k)
if (n == None or n < 0 or n > 100):
raise Exception()
except Exception, e:
return Response(status=400, response=k + 'is an invalid count. Max is 100')
# Everything ok, let's do some work
db = get_db()
# here we compute the appropiate period and ask from the database for the top likes in the daterange required
targetdate = datetime.datetime.utcnow() - gettimedelta(period)
cursor_likes = db.likes.find({"date_list" : {"$gt": targetdate}}).sort('count', pymongo.DESCENDING).limit(n)
#app.logger.debug("like_list")
likes = []
needsSort = False
for doc in cursor_likes :
#app.logger.debug(doc)
count = doc['count']
# if we have more than one date, we might need to change the count
# of likes for this period since not all of them migth be in our range
# just decrease for each one that is not in our range. If this
# happens we will have to sort
for date in doc['date_list']:
if date < targetdate:
needsSort = True
count = count - 1
like = {'image_id':doc['image_id'], 'count': count}
likes.append(like)
# Only sort the list if it needs for perf
if (needsSort):
sortedList = sorted(likes, key=lambda x: x['count'], reverse = True)
else:
sortedList = likes
resp = jsonify(likes=sortedList)
app.logger.debug("response: " + resp.data)
return resp
##
## Helper function to figure out the timedelta based on
## on the period passed to the leaderboard function.
## At this point it should be a valid period since it has been checked
def gettimedelta(period):
#24hrs, 36hrs, week, month, year'
if (period == '24hrs'):
return timedelta(days=1)
elif (period == '36hrs'):
return timedelta(days=1, hours =12)
elif (period == 'week'):
return timedelta(days=7)
elif (period == 'month'):
return timedelta(days=30)
elif (period == 'year'):
return timedelta(days=365)
###
### Root Route, doesn't do anything. just make sure we are loaded
###
@app.route('/')
def hello():
return 'Please use the API'
##
## So that we can run it in the localhost
if __name__ == '__main__':
#app.run(debug=True)
app.run()