Skip to content

Instantly share code, notes, and snippets.

@patkujawa-wf
Created December 30, 2014 19:08
Show Gist options
  • Save patkujawa-wf/41d1cf4a61abc4587507 to your computer and use it in GitHub Desktop.
Save patkujawa-wf/41d1cf4a61abc4587507 to your computer and use it in GitHub Desktop.
Cursors in google app engine example, pagination with urlsafe conversion
# Taken from http://ae-book.appspot.com/static/pgae-ndb-20121009.pdf
# Video at https://www.youtube.com/watch?v=xZsxWn58pS0#t=3184
## Cursors
# • Fetch results using an iterator, with cursors enabled:
it = query.iter(produce_cursors=True)
for result in it: # ...
# • Test whether there’s another result:
if it.has_next(): # ...
if it.probably_has_next(): # ...
# • Get a cursor after fetching results:
cursor = it.cursor_after()
# • Pass cursor to next request:
self.response.write(cursor.urlsafe())
# • In next request, reconstruct the cursor value:
cursor = ndb.Cursor.from_websafe_string(self.request.get(‘cursor’))
# • Use the cursor for the next query:
it = query.iter(start_cursor=cursor)
# • It must be the same query: kind, filters, sort orders
# Shortcut: fetch_page()
cursor = ndb.Cursor.from_websafe_string(self.request.get(‘cursor’))
(results, cursor, more) = query.fetch_page(20, start_cursor=cursor)
if more:
# render “Next” link with cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment