python - 如何修复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 并分页。请有人帮助我
解决方案
我以前为我的博客做过,我在 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
我希望它能以某种方式帮助你。干杯
推荐阅读
- postgresql - .Net Core 3.0 Npgsql 迁移问题
- java - Java Swing GUI:如何将组件从下到上而不是相反?
- c# - API 返回包含换行符等的 json。我怎样才能清理我的 json?
- unreal-engine4 - 虚幻引擎触发器总是转到 A 输出
- themes - 如何将此自定义添加到我的 Shopify 首次亮相主题?
- java - 比较对象数组元素中的特定属性
- angular - 角度未正确映射字典对象
- angular - 如何将变量(HTTP 相关)从 1 个组件发送到 2 个组件
- entity-framework - Entity Framework Core 3.0 同一张表的多对多
- mongodb - 如何“映射”一个异步迭代器?