在Flask中實(shí)現(xiàn)分頁(yè)功能可以通過在視圖函數(shù)中使用paginate
方法來實(shí)現(xiàn)。首先需要安裝flask_sqlalchemy
擴(kuò)展來實(shí)現(xiàn)數(shù)據(jù)庫(kù)查詢的分頁(yè)功能。
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:///database.db'
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
content = db.Column(db.Text)
paginate
方法實(shí)現(xiàn)分頁(yè)功能:@app.route('/')
def index():
page = request.args.get('page', 1, type=int)
per_page = 10
posts = Post.query.order_by(Post.id.desc()).paginate(page, per_page, error_out=False)
return render_template('index.html', posts=posts)
{% for post in posts.items %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}
{% if posts.has_prev %}
<a href="{{ url_for('index', page=posts.prev_num) }}">Previous</a>
{% endif %}
{% if posts.has_next %}
<a href="{{ url_for('index', page=posts.next_num) }}">Next</a>
{% endif %}
通過以上步驟,就可以實(shí)現(xiàn)在Flask應(yīng)用中的分頁(yè)功能。