Flask Snippets

This is an archived view of user-submitted snippets. Despite being
hosted on the Flask site, they are not official. No Flask
maintainer has curated or checked the snippets for security,
correctness, or design.

Simple Pagination

Unless you are using JavaScript to dynamically load more contents pagination is a neat concept to structure many items of information into multiple pages. The idea is that if you have 100 items you show 20 per page and have 5 pages in total then.

Simple Pagination Class

If you are using Flask-SQLAlchemy you can use the integrated pagination class it provides. Here is a simple pagination class that does roughly the same without the support for slicing SQLAlchemy query objects:

URLs and Views

So how do you declare URLs and views when using Pagination? The Werkzeug routing system which Flask use supports this nicely with route level defaults. You specify a “default” for page 1 for the bare URL and provide an integer wildcard for other pages:

Note how this code is returning an 404 error for all pages besides the first page if no items were there to display. This is generally a good idea.

When a user heads to /users/page/1 Flask will redirect him automatically to /users/ to keep the URL unique.

URL Generation Helper

Now how can a template generate a URL to a different page without much hassle? Because the only difference from one URL to the other is the page part in it we can provide a little helper function that wraps url_for to generate a new URL to the same endpoint with a different page:

The url_for_other_page function is not handling query strings in the URL. Just change the line :
args = request.view_args.copy() to
args = dict(request.view_args.items() + request.args.to_dict().items())
and it works fine.

Comment
by hilfi alkaff
on 2014-01-29 @ 18:50

Somehow my request.view_args is empty when I have previous search results on the paginated data. I had to use request.args.copy() instead.

What about zero
by Johnny
on 2014-12-06 @ 16:14

You are starting offset from 1. What about zero?
I am getting something like select from user limit 1,20 instead 0,20 from page number 1.

Can you somehow fix that?

Fix for zero
by Johnny
on 2014-12-06 @ 17:01

In order for zero to work in you user query you could add something like (page-1):
<pre>
users = get_users_for_page(page-1, PER_PAGE, count)
</pre>

But than query for last page will not work since you will have for example last page 10 is with -1 = 9