Skip to content

Instantly share code, notes, and snippets.

@vrySantosh
Created September 6, 2017 04:10
Show Gist options
  • Save vrySantosh/b1bbefc72ccda730ed76d9bf426a3aa5 to your computer and use it in GitHub Desktop.
Save vrySantosh/b1bbefc72ccda730ed76d9bf426a3aa5 to your computer and use it in GitHub Desktop.
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