首页 > 解决方案 > 如何修复python查询和html中的分页

问题描述

我在使用 Flask-SQLAlchemy、Flask-mysql 或 Flask-Pagination 实现分页时遇到问题。如何初始化分页。我是初学者,我是 Python 新手。

@app.route('/chats/<string:id><int:pageno>', methods=['GET', 'POST'])
 def chats(id, pageno=1):
   if id != 0:
     # Create cursor
     cur = mysql.connection.cursor()

     # Get message
     cur.execute(
         "SELECT count(id) as totalmessages FROM message WHERE 
         (msg_by=%s AND msg_to=%s) OR (msg_by=%s AND msg_to=%s) "
         "ORDER BY id DESC ", (id, session['uid'], session['uid'], id))
     chats = cur.fetchall()
     totalpages = math.ceil(chats.totalmessages / 20);
     if pageno > totalpages:
         pageno == totalpages
     else:
         cur.execute("SELECT * FROM message WHERE 
         (msg_by=%s AND msg_to=%s) OR (msg_by=%s AND msg_to=%s) "
         "ORDER BY id DESC limit " + ((pageno - 1) * 20) + ", 20",
                    (id, session['uid'], session['uid'], id))
         chats = cur.fetchall()
         # Close Connection
         cur.close()
         return render_template('chats.html', chats=chats)

     return redirect(url_for('login'))
   return redirect(url_for('login'))

我不知道从哪里开始。我想查询数据库表的所有行,将结果限制为 10 并分页。请有人帮助我

标签: pythonhtmlmysqlflaskpagination

解决方案


我以前为我的博客做过,我在 Flask-SQAlchemy 中使用了以下代码。

应用程序.py

@app.route('/blog', methods=['GET', 'POST'])
def blog():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=9)
    return render_template('blog.html', posts=posts)

现在在您的 Html 文件中使用 Jinja2:

博客.html

{% for i in posts.items %}
{{i.title}}
{{ i.body }}
{% endfor %}



{% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}

    {% if page_num %}

    {% if posts.page == page_num %}


{{ url_for('blog', page=page_num) }} {{ page_num }}

    {% else %}

{{ url_for('blog', page=page_num) }}  {{ page_num }}

    {% endif %}

    {% else %}

    ...
    {% endif %}

    {% endfor %}

https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#utilities https://riptutorial.com/flask/example/22201/pagination-route-example-with-flask-sqlalchemy-paginate

我希望它能以某种方式帮助你。干杯


推荐阅读