Created
September 6, 2017 04:10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, abort, request, jsonify | |
from models import Event | |
app = Flask(__name__) | |
@app.route('/api/v2/events/page') | |
def view(): | |
return jsonify(get_paginated_list( | |
Event, | |
'/api/v2/events/page', | |
start=request.args.get('start', 1), | |
limit=request.args.get('limit', 20) | |
)) | |
def get_paginated_list(klass, url, start, limit): | |
# check if page exists | |
results = klass.query.all() | |
count = len(results) | |
if (count < start): | |
abort(404) | |
# make response | |
obj = {} | |
obj['start'] = start | |
obj['limit'] = limit | |
obj['count'] = count | |
# make URLs | |
# make previous url | |
if start == 1: | |
obj['previous'] = '' | |
else: | |
start_copy = max(1, start - limit) | |
limit_copy = start - 1 | |
obj['previous'] = url + '?start=%d&limit=%d' % (start_copy, limit_copy) | |
# make next url | |
if start + limit > count: | |
obj['next'] = '' | |
else: | |
start_copy = start + limit | |
obj['next'] = url + '?start=%d&limit=%d' % (start_copy, limit) | |
# finally extract result according to bounds | |
obj['results'] = results[(start - 1):(start - 1 + limit)] | |
return obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment