flask_paginate 是 Flask 框架的一个分页扩展,用于处理分页相关的功能。它可以帮助你在 Flask Web 应用程序中实现分页功能,让用户可以浏览大量数据的不同部分。本篇博文重点讲述在Web开发中,用paginate把所有数据进行分页展示,首先通过运用第三方库实现后端分页,然后再自己编写一个分页类实现。
Flask-SQLAlchemy
是 Flask 框架的一个扩展,提供了对 SQL 数据库的集成支持。它基于 SQLAlchemy 构建,简化了在 Flask 应用中使用数据库的操作。
安装 Flask-SQLAlchemy
:
pip install Flask-SQLAlchemy
Flask-SQLAlchemy的使用很简单,如下是一些简单的用法;
from flask import Flask
from sqlalchemy import not_,or_,and_,desc
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# url的格式为:数据库的协议://用户名:密码@ip地址:端口号(默认可以不写)/数据库名
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
# 为了解决控制台的提示
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# 创建数据库的操作对象
db = SQLAlchemy(app)
# 创建规则表
class RoleDB(db.Model):
__tablename__ = "role"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), unique=True)
# 增加反查外键关联到UserDB
users = db.relationship('UserDB', backref="role")
# 当调用 Role.query.all() 会触发输出
def __repr__(self):
return "Role: %s | %s" % (self.id, self.name)
# 创建用户表
class UserDB(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), unique=True)
email = db.Column(db.String(32), unique=True)
password = db.Column(db.String(16))
# 关联到RuleDB表中的ID上面
role_id = db.Column(db.Integer, db.ForeignKey("role.id"))
# 当调用 RoleDB.query.all() 会触发输出
def __repr__(self):
return "User: %s | %s | %s | %s" % (self.id, self.name, self.password, self.role_id)
@app.route('/')
def index():
# 此处查询会走类内 __repr__ 输出
print("查询所有用户数据: ", UserDB.query.all())
print("查询所有规则数据: ", RoleDB.query.all())
print("查询有多少个用户: ", UserDB.query.count())
print("查询第一个用户: ", UserDB.query.first())
# 查询过滤器
print("查询第一条: ", UserDB.query.get(1))
print("查询过滤器(类名+属性名): ", UserDB.query.filter(UserDB.id == 4).first())
print("查询过滤器(属性名): ", UserDB.query.filter_by(id=4).first())
# 查询名字结尾字符为g的所有数据 [开始/包含]
print(UserDB.query.filter(UserDB.name.endswith("g")).all())
print(UserDB.query.filter(UserDB.name.contains("g")).all())
# 查询名字不等于wang的所有数据 [2种方式]
print(UserDB.query.filter(not_(UserDB.name == "wang")).all())
print(UserDB.query.filter(UserDB.name != "wang").all())
# 查询 [名字和邮箱] 都以li开头的所有数据 [2种方式]
print(UserDB.query.filter(and_(UserDB.name.startswith("li"),UserDB.email.startswith("li"))).all())
print(UserDB.query.filter(UserDB.name.startswith("li"), UserDB.email.startswith("li")).all())
# 查询password是 123456 或者 email 以 lyshark.com 结尾的所有数据
print(UserDB.query.filter(or_(UserDB.password=='123456', UserDB.email.endswith('lyshark.com'))).all())
# 查询id为 [1, 3, 5, 7, 9] 的用户列表
print(UserDB.query.filter(UserDB.id.in_([1, 3, 5, 7, 9])).all())
# 查询name为liu的角色数据:关系引用
print(UserDB.query.filter_by(name="liu").first().role.name)
# 查询所有用户数据 并以邮箱排序 [升序/降序]
print("升序: ", UserDB.query.order_by("email").all())
print("降序: ", UserDB.query.order_by(desc("email")).all())
# 查询第2页的数据,每页只显示3条数据
pages = UserDB.query.paginate(2,3,False)
print("查询结果: {} 总页数: {} 当前页数: {}".format(pages.items,pages.pages,pages.page))
# 完整查询调用写法
ref = db.session.query(UserDB).filter(UserDB.name == "wang").all()
print(ref)
return "success"
if __name__ == "__main__":
# 初始化数据表
db.drop_all()
db.create_all()
# 插入两个规则记录
role_admin = RoleDB(name="admin")
db.session.add(role_admin)
role_lyshark = RoleDB(name="lyshark")
db.session.add(role_lyshark)
db.session.commit()
try:
ua = UserDB(name='wang', email='[email protected]', password='123456', role_id=role_admin.id)
ub = UserDB(name='zhang', email='[email protected]', password='201512', role_id=role_lyshark.id)
uc = UserDB(name='chen', email='[email protected]', password='987654', role_id=role_lyshark.id)
ud = UserDB(name='zhou', email='[email protected]', password='456789', role_id=role_admin.id)
ue = UserDB(name='tang', email='[email protected]', password='158104', role_id=role_lyshark.id)
uf = UserDB(name='wu', email='[email protected]', password='5623514', role_id=role_lyshark.id)
ug = UserDB(name='qian', email='[email protected]', password='1543567', role_id=role_admin.id)
uh = UserDB(name='liu', email='[email protected]', password='867322', role_id=role_admin.id)
ui = UserDB(name='li', email='[email protected]', password='4526342', role_id=role_lyshark.id)
uj = UserDB(name='sun', email='[email protected]', password='235523', role_id=role_lyshark.id)
db.session.add_all([ua, ub, uc, ud, ue, uf, ug, uh, ui, uj])
db.session.commit()
except Exception as e:
# 插入失败自动回滚
db.session.rollback()
raise e
app.run(debug=True)
Flask-SQLAlchemy 分页插件为 Flask 应用提供了便捷而强大的分页功能,通过 paginate()
方法返回的 Pagination
类对象,开发者能够轻松实现对大型数据集的分页展示。该插件基于 Flask-SQLAlchemy
扩展构建,简化了在 Flask
应用中进行数据库查询的分页操作。通过灵活的配置选项,开发者可以高效地管理和展示数据,提升用户体验,是构建数据驱动 Web
应用的重要利器。本文将深入介绍 Flask-SQLAlchemy
分页插件的基本使用方法以及常见配置选项,帮助开发者快速上手并充分发挥其强大的分页功能。
前端部分使用bootstrap
实现分页组件,新建前端index.html
文件,代码如下;
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/bootstrap/5.1.3/css/bootstrap.min.css">
head>
<body>
<div class="box box-primary">
<div class="box-body table-responsive no-padding">
<table class="table table-sm table-hover">
<thread>
<tr class="table-success">
<th>idth>
<th>nameth>
<th>emailth>
<th>passwordth>
tr>
thread>
<tbody>
{% for item in page_data.items %}
<tr class="table-primary">
<td>{{ item.id }}td>
<td>{{ item.name }}td>
<td>{{ item.email }}td>
<td>{{ item.password }}td>
tr>
{% endfor %}
tbody>
table>
div>
<div class="box-footer clearfix">
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
{% if page_data %}
<ul class="pagination">
<li class="page-item"><a class="page-link" href="./1">首页a>li>
{% if page_data.has_prev %}
<li class="page-item"><a class="page-link" href="{{ page_data.prev_num }}">上一页a>li>
{% else %}
<li class="page-item" class="disabled"><a class="page-link" href="#">上一页a>li>
{% endif %}
<p>{{ page_data.page }}p> / <p>{{ page_data.pages }}p>
{% if page_data.has_next %}
<li class="page-item"><a class="page-link" href="{{ page_data.next_num }}">下一页a>li>
{% else %}
<li class="page-item" class="disabled"><a class="page-link" href="#">下一页a>li>
{% endif %}
<li class="page-item"><a class="page-link" href="{{ page_data.pages }}">尾页a>li>
ul>
{% endif %}
nav>
div>
div>
body>
html>
使用组件内的过滤器分页是非常简单的一件事,只需要调用参数后返回,后端app.py
代码如下;
from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__, template_folder="./tempate",static_folder="./tempate")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
# 设置每次请求结束后会自动提交数据库的改动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询时显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = False
# 创建数据库的操作对象
db = SQLAlchemy(app)
# 创建用户表
class UserDB(db.Model):
__tablename__="user"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32))
email = db.Column(db.String(32))
password = db.Column(db.String(32))
def __init__(self,name,email,password):
self.name = name
self.email = email
self.password = password
def __repr_(self):
return 'User %s'%self.name
@app.route("/")
def index():
return ""
@app.route("/page/" )
def page(page_number=None):
if page_number is None:
page_number = 1
page = db.session.query(UserDB).paginate(page=page_number,per_page=10,max_per_page=15)
return render_template("index.html", page_data = page)
if __name__ == "__main__":
# 初始化数据表
db.drop_all()
db.create_all()
try:
ua = UserDB(name='wang', email='[email protected]', password='123456')
ub = UserDB(name='zhang', email='[email protected]', password='201512')
uc = UserDB(name='chen', email='[email protected]', password='987654')
ud = UserDB(name='zhou', email='[email protected]', password='456789')
ue = UserDB(name='tang', email='[email protected]', password='158104')
uf = UserDB(name='wu', email='[email protected]', password='5623514')
ug = UserDB(name='qian', email='[email protected]', password='1543567')
uh = UserDB(name='liu', email='[email protected]', password='867322')
ui = UserDB(name='li', email='[email protected]', password='4526342')
uj = UserDB(name='sun', email='[email protected]', password='235523')
db.session.add_all([ua, ub, uc, ud, ue, uf, ug, uh, ui, uj,uj,uj,uj,uj,uj,uj,uj,uj])
db.session.commit()
except Exception as e:
# 插入失败自动回滚
db.session.rollback()
raise e
app.run(debug=True)
Flask-Paginate 是 Flask 框架中的一个重要插件,为开发者提供了便捷而灵活的分页解决方案。通过结合 Flask 官方的分页部件,这个插件能够轻松地实现对大量数据的分页展示,为用户提供更友好的浏览体验。本文将深入介绍 Flask-Paginate 的核心功能、使用方法以及与数据库查询的协同操作,帮助开发者更好地利用这一工具来优化 Web 应用的分页展示。
前端部分使用bootstrap
实现分页组件,新建前端index.html
文件,代码如下;
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/bootstrap/5.1.3/css/bootstrap.min.css">
head>
<body>
<table class="table table-sm table-hover">
<thead>
<tr class="table-success">
<th>序号th>
<th>用户IDth>
<th>用户名称th>
<th>用户邮箱th>
<th>用户密码th>
tr>
thead>
<tbody>
{% for article in articles %}
<tr class="table-primary">
<td>{{ loop.index }}td>
<td>{{ article.id }}td>
<td>{{ article.name }}td>
<td>{{ article.email }}td>
<td>{{ article.password }}td>
tr>
{% endfor %}
tbody>
table>
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
<ul class="pagination">
<li class="page-item"><a class="page-link" href="./page=1">首页a>li>
{% if pagination.has_prev %}
<li class="page-item"><a class="page-link" href="./page={{ prve_num }}">上一页a>li>
{% endif %}
{% for item in pageRange %}
{% if item == currentPage %}
<li class="page-item active"><a class="page-link" href="./page={{ item }}">{{ item }}a>li>
{% else %}
<li class="page-item"><a class="page-link" href="./page={{ item }}">{{ item }}a>li>
{% endif %}
{% endfor %}
{% if next_end %}
<li class="page-item"><a class="page-link" href="./page={{ next_num }}">下一页a>li>
{% endif %}
<li class="page-item"><a class="page-link" href="./page={{ PageCount }}">尾页a>li>
ul>
nav>
<div style="text-align: center;" class="alert alert-dark">
统计: {{ pagination.page }}/{{ PageCount }} 共查询到:{{ pagination.total }} 条数据 页码列表:{{ pageRange }}
div>
body>
html>
后端就是对请求的响应,前端用户通过GET方式访问,后端获得用户页面数,查询后动态展示出来即可。
from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
from flask_paginate import Pagination,get_page_parameter
import math
app = Flask(__name__, template_folder="./tempate",static_folder="./tempate")
# url的格式为:数据库的协议://用户名:密码@ip地址:端口号(默认可以不写)/数据库名
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
# 设置每次请求结束后会自动提交数据库的改动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询时显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = False
# 创建数据库的操作对象
db = SQLAlchemy(app)
# 创建用户表
class UserDB(db.Model):
__tablename__="user"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32))
email = db.Column(db.String(32))
password = db.Column(db.String(32))
def __init__(self,name,email,password):
self.name = name
self.email = email
self.password = password
def __repr_(self):
return 'User %s'%self.name
@app.route("/")
def index():
return """"""
@app.route("/page=" )
def GetPages(id):
# 默认每页显示10个元素
PER_PAGE = 10
total = db.session.query(UserDB).count()
print("总记录 {} 条".format(total))
currentPage = request.args.get(get_page_parameter(),type=int,default=int(id))
print("当前页码ID为 {}".format(currentPage))
start = (currentPage-1)*PER_PAGE # 分页起始位置
end = start+PER_PAGE # 分页结束位置
print("起始位置 {} 结束位置 {}".format(start,end))
prev_num = int(currentPage)-1
next_num = int(currentPage)+1
print("上一页页码 {} 下一页页码 {}".format(prev_num,next_num))
# 计算出需要切割的页数
page_count = math.ceil(total/PER_PAGE)
print("切割页数 {}".format(page_count))
pagination = Pagination(page=currentPage,total=total)
# 执行数据库切片
articles = db.session.query(UserDB).slice(start,end)
# 判断,如果next_end大于总数说明到最后了
if currentPage>=math.ceil(total/PER_PAGE):
# 那么我们就将next_end设置为0,前端就不执行显示了
next_end=0
else:
next_end=1
# -------------------------------------------------
# 此页面是扩展部分,用于生成当前页码,并填充到前端
# 如果总页数小于15则一次性生成页码即可
if page_count < 15:
pageRange = range(1,page_count+1)
# 总页数大于15则需要分情况生成
elif page_count > 15:
# 说明是第一页
if currentPage-5 < 1:
pageRange = range(1,11)
# 说明是最后一页
elif currentPage+5 > page_count:
pageRange = range(currentPage-5,page_count)
# 说明是中间页
else:
pageRange = range(currentPage-5,currentPage+5)
# 如果都不是则返回总数
else:
pageRange = page_count
print("生成的当前页码: {}".format(pageRange))
context = {
'pagination': pagination,
'articles': articles,
'prve_num': prev_num,
'next_num': next_num,
'PageCount': page_count,
'pageRange': pageRange,
'next_end': next_end,
"currentPage": currentPage
}
return render_template('index.html',**context)
if __name__ == "__main__":
db.drop_all()
db.create_all()
try:
ua = UserDB(name='wang', email='[email protected]', password='123456')
ub = UserDB(name='zhang', email='[email protected]', password='201512')
uc = UserDB(name='chen', email='[email protected]', password='987654')
ud = UserDB(name='zhou', email='[email protected]', password='456789')
ue = UserDB(name='tang', email='[email protected]', password='158104')
uf = UserDB(name='wu', email='[email protected]', password='5623514')
ug = UserDB(name='qian', email='[email protected]', password='1543567')
uh = UserDB(name='liu', email='[email protected]', password='867322')
ui = UserDB(name='li', email='[email protected]', password='4526342')
uj = UserDB(name='sun', email='[email protected]', password='235523')
db.session.add_all([ua, ub, uc, ud, ue, uf, ug, uh, ui, uj,uj,uj,uj,uj,uj,uj,uj,uj])
db.session.commit()
except Exception as e:
# 插入失败自动回滚
db.session.rollback()
raise e
app.run(debug=True)
前端部分使用bootstrap
实现分页组件,新建前端index.html
文件,代码如下;
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<link rel="stylesheet" href="https://www.lyshark.com/javascript/bootstrap/5.1.3/css/bootstrap.min.css">
head>
<body>
<table class="table table-sm table-hover">
<thead>
<tr class="table-success">
<th>用户IDth>
<th>用户名称th>
<th>用户邮箱th>
<th>用户密码th>
tr>
thead>
<tbody>
{% for article in articles %}
<tr class="table-primary">
<td>{{ article.id }}td>
<td>{{ article.name }}td>
<td>{{ article.email }}td>
<td>{{ article.password }}td>
tr>
{% endfor %}
tbody>
table>
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
<ul class="pagination">
{{ html|safe }}
ul>
nav>
body>
html>
首先需要创建一个pager.py
文件,里面包含一个Pagination
分页类部件。
import copy
from urllib.parse import urlencode
class Pagination(object):
def __init__(self,current_page,total_count,base_url,params,per_page_count=10,max_pager_count=11):
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
if current_page <=0:
current_page = 1
self.current_page = current_page
# 数据总条数
self.total_count = total_count
# 每页显示10条数据
self.per_page_count = per_page_count
# 页面上应该显示的最大页码
max_page_num, div = divmod(total_count, per_page_count)
if div:
max_page_num += 1
self.max_page_num = max_page_num
# 页面上默认显示11个页码(当前页在中间)
self.max_pager_count = max_pager_count
self.half_max_pager_count = int((max_pager_count - 1) / 2)
# URL前缀
self.base_url = base_url
# request.GET
params = copy.deepcopy(params)
# params._mutable = True
get_dict = params.to_dict()
# 包含当前列表页面所有的搜/索条件
self.params = get_dict
@property
def start(self):
return (self.current_page - 1) * self.per_page_count
@property
def end(self):
return self.current_page * self.per_page_count
def page_html(self):
# 如果总页数 <= 11
if self.max_page_num <= self.max_pager_count:
pager_start = 1
pager_end = self.max_page_num
# 如果总页数 > 11
else:
# 如果当前页 <= 5
if self.current_page <= self.half_max_pager_count:
pager_start = 1
pager_end = self.max_pager_count
else:
# 当前页 + 5 > 总页码
if (self.current_page + self.half_max_pager_count) > self.max_page_num:
pager_end = self.max_page_num
pager_start = self.max_page_num - self.max_pager_count + 1 #倒这数11个
else:
pager_start = self.current_page - self.half_max_pager_count
pager_end = self.current_page + self.half_max_pager_count
page_html_list = []
# 首页
self.params['page'] = 1
first_page = '首页 ' % (self.base_url,urlencode(self.params),)
page_html_list.append(first_page)
# 上一页
self.params["page"] = self.current_page - 1
if self.params["page"] < 1:
pervious_page = '<li class="page-item" class="disabled"><a class="page-link" \
href="%s?%s" aria-label="Previous">上一页</span></a></li>' % (self.base_url, urlencode(self.params))
else:
pervious_page = '<li class="page-item"><a class="page-link" href = "%s?%s" \
aria-label = "Previous" >上一页</span></a></li>' % ( self.base_url, urlencode(self.params))
page_html_list.append(pervious_page)
# 中间页码
for i in range(pager_start, pager_end + 1):
self.params['page'] = i
if i == self.current_page:
temp = '<li class="page-item active" class="active"><a class="page-link" \
href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
else:
temp = '<li class="page-item"><a class="page-link" \
href="%s?%s">%s</a></li>' % (self.base_url,urlencode(self.params), i,)
page_html_list.append(temp)
# 下一页
self.params["page"] = self.current_page + 1
if self.params["page"] > self.max_page_num:
self.params["page"] = self.current_page
next_page = '<li class="page-item" class="disabled"><a class="page-link" \
href = "%s?%s" aria-label = "Next">下一页</span></a></li >' % (self.base_url, urlencode(self.params))
else:
next_page = '<li class="page-item"><a class="page-link" href = "%s?%s" \
aria-label = "Next">下一页</span></a></li>' % (self.base_url, urlencode(self.params))
page_html_list.append(next_page)
# 尾页
self.params['page'] = self.max_page_num
last_page = '尾页 ' % (self.base_url, urlencode(self.params),)
page_html_list.append(last_page)
return ''.join(page_html_list)
主函数main.py
则直接import Pagination
导入分页类,然后调用Pagination
函数即可实现分页了。
from flask import Flask,render_template,request
from flask_sqlalchemy import SQLAlchemy
from pager import Pagination
app = Flask(__name__, template_folder="./tempate",static_folder="./tempate")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
# 设置每次请求结束后会自动提交数据库的改动
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 查询时显示原始SQL语句
app.config['SQLALCHEMY_ECHO'] = False
# 创建数据库的操作对象
db = SQLAlchemy(app)
# 创建用户表
class UserDB(db.Model):
__tablename__="user"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(32))
email = db.Column(db.String(32))
password = db.Column(db.String(32))
def __init__(self,name,email,password):
self.name = name
self.email = email
self.password = password
def __repr_(self):
return 'User %s'%self.name
@app.route("/")
def index():
total = db.session.query(UserDB).count()
print("查询总记录数: {}".format(total))
page_number = request.args.get("page", 1)
print("当前传入页码: {}".format(page_number))
# 分页类 [ Pagination(传入页码/总记录数/分页URL前缀/传入数据params/每页显示数/最大显示页码 )]
Page = Pagination(page_number, total, request.path, request.args, per_page_count=10, max_pager_count=15)
# 对数据切片
index = db.session.query(UserDB)[Page.start:Page.end]
print("页面切片: {}".format(index))
# 渲染页面
html = Page.page_html()
print("渲染页码页面: {}".format(html))
return render_template("index.html",articles=index,html=html)
if __name__ == "__main__":
# 初始化数据表
db.drop_all()
db.create_all()
try:
ua = UserDB(name='wang', email='[email protected]', password='123456')
ub = UserDB(name='zhang', email='[email protected]', password='201512')
uc = UserDB(name='chen', email='[email protected]', password='987654')
ud = UserDB(name='zhou', email='[email protected]', password='456789')
ue = UserDB(name='tang', email='[email protected]', password='158104')
uf = UserDB(name='wu', email='[email protected]', password='5623514')
ug = UserDB(name='qian', email='[email protected]', password='1543567')
uh = UserDB(name='liu', email='[email protected]', password='867322')
ui = UserDB(name='li', email='[email protected]', password='4526342')
uj = UserDB(name='sun', email='[email protected]', password='235523')
db.session.add_all([ua, ub, uc, ud, ue, uf, ug, uh, ui, uj,uj,uj,uj,uj,uj,uj,uj,uj])
db.session.commit()
except Exception as e:
# 插入失败自动回滚
db.session.rollback()
raise e
app.run(debug=True)