Flask Pagination Route Example with flask-sqlalchemy Paginate


Example

In this example we use a parameter in the route to specify the page number. We set a default of 1 in the function parameter page=1. We have a User object in the database and we query it, ordering in descending order, showing latest users first. We then use the paginate method of the query object in flask-sqlalchemy. We then pass this to render_template to be rendered.

@app.route('/users')
@app.route('/users/page/<int:page>')
def all_users(page=1):
    try:
        users_list = User.query.order_by(
            User.id.desc()
        ).paginate(page, per_page=USERS_PER_PAGE)
    except OperationalError:
        flash("No users in the database.")
        users_list = None

    return render_template(
        'users.html',
        users_list=users_list,
        form=form
    )