Python Flask SQLAlchemy Pagination

I recommend using Flask-SQLAlchemy's pagination:

There's a well-written example here:

Here's the basic idea for the view:

def view(page=1):
    per_page = 10
    posts = Posts.query.order_by(Posts.time.desc()).paginate(page,per_page,error_out=False)
    return render_template('view.html',posts=posts)

And then for the template (I don't know your posts model so I made something up):


{% for post in posts.items %}
  {{ post.post_name }} post body: <b>{{ post.body }}</b>
{% endfor %}
{% if posts.has_prev %}<a href="{{ url_for('view', page=posts.prev_num) }}">&lt;&lt; Newer posts</a>{% else %}&lt;&lt; Newer posts{% endif %} | 
{% if posts.has_next %}<a href="{{ url_for('view', page=posts.next_num) }}">Older posts &gt;&gt;</a>{% else %}Older posts &gt;&gt;{% endif %}



@app.route('/', methods=['GET'], defaults={"page": 1}) 
@app.route('/<int:page>', methods=['GET'])
def index(page):
    page = page
    per_page = 2
    users = User.query.paginate(page,per_page,error_out=False)
    # print("Result......", users)
    return render_template("index.html", users=users)

in the View

{% for user in users.items %}
    <h1> {{ }} </h1>
{% endfor %}

<nav aria-label="Page navigation example">
                <ul class="pagination">
                    {% if users.has_prev %}
                      <li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.prev_num) }}">Previous</a></li>
                    {% else %}
                      <li class="page-item"><a class="page-link btn disabled" href="#">Previous</a></li>
                    {% endif %}

                    {% if users.has_next %}
                      <li class="page-item"> <a class="page-link" href="{{ url_for('index', page=users.next_num) }}">Next</a></li>
                    {% else %}
                      <li class="page-item"><a class="page-link btn disabled" href="#">Next</a></li>
                    {% endif %}