From 19a45f3f6fe993d0bb540b1a6d5c77d508f0490f Mon Sep 17 00:00:00 2001 From: Alan Orth Date: Mon, 24 Sep 2018 16:07:26 +0300 Subject: [PATCH] app.py: Add route to page through all item statistics This route exposes all item statistics and uses the limit and offset parameters to control paging throug the result set. The logic here is extremely easy thanks to the brilliant LIMIT and OFFSET features of SQLite (of course the SQL query sorts the results by some unique field to ensure the order is already the same). --- app.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/app.py b/app.py index fccece0..6eb12da 100644 --- a/app.py +++ b/app.py @@ -9,6 +9,41 @@ from solr import solr_connection db = database_connection_ro() solr = solr_connection() +class AllItemsResource: + def on_get(self, req, resp): + """Handles GET requests""" + # Return HTTPBadRequest if id parameter is not present and valid + limit = req.get_param_as_int("limit", min=0, max=100) or 100 + page = req.get_param_as_int("page", min=0) or 0 + offset = limit * page + + cursor = db.cursor() + + # get total number of items so we can estimate the pages + cursor.execute('SELECT COUNT(id) FROM items') + pages = round(cursor.fetchone()[0] / limit) + + # get statistics, ordered by id, and use limit and offset to page through results + cursor.execute('SELECT id, views, downloads FROM items ORDER BY id ASC LIMIT {0} OFFSET {1}'.format(limit, offset)) + results = cursor.fetchmany(limit) + cursor.close() + + # create a list to hold dicts of item stats + statistics = list() + + # iterate over results and build statistics object + for item in results: + statistics.append({ 'id': item['id'], 'views': item['views'], 'downloads': item['downloads'] }) + + message = { + 'currentPage': page, + 'totalPages': pages, + 'limit': limit, + 'statistics': statistics + } + + resp.media = message + class ItemResource: def on_get(self, req, resp, item_id): """Handles GET requests""" @@ -27,6 +62,7 @@ class ItemResource: resp.media = statistics api = falcon.API() +api.add_route('/', AllItemsResource()) api.add_route('/item/{item_id:int}', ItemResource()) # vim: set sw=4 ts=4 expandtab: