Python Flask SQL Alchemy Pagination

I'm having trouble implementing pagination using Flask-SQLAlchemy or Flask-Pagination, either. I'm not sure how to initialize pagination, page setup, page definition, resentment, etc. I come from PHP, completely new to Python.

I request all messages in my database

posts = Posts.query.order_by(Posts.time.desc()).all()

I considered the following examples:

I am really confused about what to do, the information I find is very different between the articles. This left me confused and not knowing where to start. I want to query all rows of a database table, limit the results to 20 and paginate. I do not see this clearly.

+4
source share
1 answer

I recommend using flash-partitioning-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/2.1/api/?highlight=pagination#flask.ext.sqlalchemy.Pagination

An example is well written here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ix-pagination

Here is the basic idea for the presentation:

@app.route('/myview/<int:page>',methods=['GET'])
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 message model, so I did something):

<html>
  <head>
    Posts
  </head>
  <body>

{% for post in posts.items %}
<p>
  {{ post.post_name }} post body: <b>{{ post.body }}</b>
</p>
{% 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 %}

  </body>
</html>
+8
source

Source: https://habr.com/ru/post/1673539/


All Articles