Python中Flask分页只显示一页是什么情况?

如图显示,如果是page=2,则总页数是 33 页,但是page=1的时候总页数就只有 1 页了。百思不得其解
Python中Flask分页只显示一页是什么情况?
2 回复
遇到Flask分页只显示一页,通常是分页参数没正确传到查询里。最常见的原因是没在查询上调用.paginate()方法,或者传的页码、每页数量参数不对。
看个典型例子,假设你用的是Flask-SQLAlchemy:
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
@app.route('/posts')
def posts():
# 错误写法:直接切片,这样永远只有一页
# page = request.args.get('page', 1, type=int)
# posts = Post.query.all()[(page-1)*10:page*10] # 错误!
# 正确写法:使用paginate方法
page = request.args.get('page', 1, type=int)
per_page = 10
# 关键在这里:paginate会自动处理分页逻辑
pagination = Post.query.paginate(page=page, per_page=per_page, error_out=False)
return render_template('posts.html',
posts=pagination.items,
pagination=pagination)
if __name__ == '__main__':
app.run(debug=True)
模板里要这样显示分页链接(posts.html):
{% for post in posts %}
<h2>{{ post.title }}</h2>
{% endfor %}
<div class="pagination">
{% if pagination.has_prev %}
<a href="{{ url_for('posts', page=pagination.prev_num) }}">上一页</a>
{% endif %}
{% for page_num in pagination.iter_pages() %}
{% if page_num %}
<a href="{{ url_for('posts', page=page_num) }}">{{ page_num }}</a>
{% else %}
...
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<a href="{{ url_for('posts', page=pagination.next_num) }}">下一页</a>
{% endif %}
</div>
检查要点:
- 确保查询对象调用了
.paginate(),不是.all()或.slice() - 模板中要用
pagination.iter_pages()生成页码,不是自己算 - URL参数名要一致,默认是
page
总结:用对paginate方法就行。
想问一下我这个账号因为什么降权了?

