Created
December 21, 2017 16:58
-
-
Save samedhi/ac371892a21bea6fc1f13025320f911f to your computer and use it in GitHub Desktop.
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 app import app | |
from flask import jsonify, Flask | |
from google.appengine.ext import ndb | |
from google.appengine.ext.ndb import metadata | |
from google.appengine.datastore.datastore_query import Cursor | |
app = Flask(__name__) | |
def paginate(kind, urlsafe_cursor=None): | |
""" | |
Starts (or continues) pagination of keys in the datastore | |
RESPONSE Body (as JSON) | |
{ | |
cursor: CURSOR, | |
keys: [URLSAFE_KEY_1, URLSAFE_KEY_2, ..., URLSAFE_KEY_N] | |
} | |
WHERE: | |
CURSOR - A opaque String used for pagination | |
URLSAFE_KEY_X - A ndb.Key.urlsafe() value | |
""" | |
klass = ndb.Model._lookup_model(kind) | |
c = 100 | |
cursor = Cursor(urlsafe=urlsafe_cursor) if urlsafe_cursor else None | |
es, next_cursor, _ = klass.query().fetch_page(c, start_cursor=cursor) | |
d = {'keys': [entity.key.urlsafe() for entity in es]} | |
if next_cursor: | |
d['cursor'] = next_cursor.urlsafe() | |
return jsonify(d) | |
@app.route('/paginate/<kind>') | |
def start_pagination(kind): | |
return paginate(kind) | |
@app.route('/paginate/<kind>/<cursor>') | |
def continue_pagination(kind, cursor): | |
return paginate(kind, cursor) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment