flask_paginate 是 Flask 框架的一个分页扩展,用于处理分页相关的功能。它可以帮助你在 Flask Web 应用程序中实现分页功能,让用户可以浏览大量数据的不同部分。本篇博文重点讲述在Web开发中,用paginate把所有数据进行分页展示,首先通过运用第三方库实现后端分页,然后再自己编写一个分页类实现。
flask_sqlalchemy
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 SQLAlchemyapp = 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)# 增加反查外键关联到UserDBusers = 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='wang@163.com', password='123456', role_id=role_admin.id)ub = UserDB(name='zhang', email='zhang@189.com', password='201512', role_id=role_lyshark.id)uc = UserDB(name='chen', email='chen@126.com', password='987654', role_id=role_lyshark.id)ud = UserDB(name='zhou', email='zhou@163.com', password='456789', role_id=role_admin.id)ue = UserDB(name='tang', email='tang@lyshark.com', password='158104', role_id=role_lyshark.id)uf = UserDB(name='wu', email='wu@gmail.com', password='5623514', role_id=role_lyshark.id)ug = UserDB(name='qian', email='qian@gmail.com', password='1543567', role_id=role_admin.id)uh = UserDB(name='liu', email='liu@lyshark.com', password='867322', role_id=role_admin.id)ui = UserDB(name='li', email='li@163.com', password='4526342', role_id=role_lyshark.id)uj = UserDB(name='sun', email='sun@163.com', 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 eapp.run(debug=True)
flask_sqlalchemy 分页组件
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>Title</title><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>id</th><th>name</th><th>email</th><th>password</th></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 %}<!--{% for item in page_data.iter_pages() %}{% if item == page_data.page %}<li class="page-item active"><a class="page-link" href="{{ item }}">{{ item }}</a></li>{% else %}<li class="page-item"><a class="page-link" href="{{ item }}">{{ item }}</a></li>{% endif %}{% endfor %}--><!-- 当前页的页码/总页码 --><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 SQLAlchemyapp = 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 = nameself.email = emailself.password = passworddef __repr_(self):return 'User %s'%self.name@app.route("/")
def index():return "<script>window.location.href='./page/1'</script>"@app.route("/page/<int:page_number>")
def page(page_number=None):if page_number is None:page_number = 1page = 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='wang@163.com', password='123456')ub = UserDB(name='zhang', email='zhang@189.com', password='201512')uc = UserDB(name='chen', email='chen@126.com', password='987654')ud = UserDB(name='zhou', email='zhou@163.com', password='456789')ue = UserDB(name='tang', email='tang@lyshark.com', password='158104')uf = UserDB(name='wu', email='wu@gmail.com', password='5623514')ug = UserDB(name='qian', email='qian@gmail.com', password='1543567')uh = UserDB(name='liu', email='liu@lyshark.com', password='867322')ui = UserDB(name='li', email='li@163.com', password='4526342')uj = UserDB(name='sun', email='sun@163.com', 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 eapp.run(debug=True)
flask_paginate 分页组件
Flask-Paginate 是 Flask 框架中的一个重要插件,为开发者提供了便捷而灵活的分页解决方案。通过结合 Flask 官方的分页部件,这个插件能够轻松地实现对大量数据的分页展示,为用户提供更友好的浏览体验。本文将深入介绍 Flask-Paginate 的核心功能、使用方法以及与数据库查询的协同操作,帮助开发者更好地利用这一工具来优化 Web 应用的分页展示。
前端部分使用bootstrap
实现分页组件,新建前端index.html
文件,代码如下;
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><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>用户ID</th><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 mathapp = 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 = nameself.email = emailself.password = passworddef __repr_(self):return 'User %s'%self.name@app.route("/")
def index():return """<script>window.location.href="./page=1"</script>"""@app.route("/page=<int:id>")
def GetPages(id):# 默认每页显示10个元素PER_PAGE = 10total = 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)-1next_num = int(currentPage)+1print("上一页页码 {} 下一页页码 {}".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=0else: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_countprint("生成的当前页码: {}".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='wang@163.com', password='123456')ub = UserDB(name='zhang', email='zhang@189.com', password='201512')uc = UserDB(name='chen', email='chen@126.com', password='987654')ud = UserDB(name='zhou', email='zhou@163.com', password='456789')ue = UserDB(name='tang', email='tang@lyshark.com', password='158104')uf = UserDB(name='wu', email='wu@gmail.com', password='5623514')ug = UserDB(name='qian', email='qian@gmail.com', password='1543567')uh = UserDB(name='liu', email='liu@lyshark.com', password='867322')ui = UserDB(name='li', email='li@163.com', password='4526342')uj = UserDB(name='sun', email='sun@163.com', 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 eapp.run(debug=True)
Pagination 自写分页器
前端部分使用bootstrap
实现分页组件,新建前端index.html
文件,代码如下;
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><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>用户ID</th><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 urlencodeclass 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 = 1if current_page <=0:current_page = 1self.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 += 1self.max_page_num = max_page_num# 页面上默认显示11个页码(当前页在中间)self.max_pager_count = max_pager_countself.half_max_pager_count = int((max_pager_count - 1) / 2)# URL前缀self.base_url = base_url# request.GETparams = copy.deepcopy(params)# params._mutable = Trueget_dict = params.to_dict()# 包含当前列表页面所有的搜/索条件self.params = get_dict@propertydef start(self):return (self.current_page - 1) * self.per_page_count@propertydef end(self):return self.current_page * self.per_page_countdef page_html(self):# 如果总页数 <= 11if self.max_page_num <= self.max_pager_count:pager_start = 1pager_end = self.max_page_num# 如果总页数 > 11else:# 如果当前页 <= 5if self.current_page <= self.half_max_pager_count:pager_start = 1pager_end = self.max_pager_countelse:# 当前页 + 5 > 总页码if (self.current_page + self.half_max_pager_count) > self.max_page_num:pager_end = self.max_page_numpager_start = self.max_page_num - self.max_pager_count + 1 #倒这数11个else:pager_start = self.current_page - self.half_max_pager_countpager_end = self.current_page + self.half_max_pager_countpage_html_list = []# 首页self.params['page'] = 1first_page = '<li class="page-item"><a class="page-link" href="%s?%s">首页</a></li>' % (self.base_url,urlencode(self.params),)page_html_list.append(first_page)# 上一页self.params["page"] = self.current_page - 1if 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'] = iif 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 + 1if self.params["page"] > self.max_page_num:self.params["page"] = self.current_pagenext_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_numlast_page = '<li class="page-item"><a class="page-link" href="%s?%s">尾页</a></li>' % (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 Paginationapp = 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 = nameself.email = emailself.password = passworddef __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='wang@163.com', password='123456')ub = UserDB(name='zhang', email='zhang@189.com', password='201512')uc = UserDB(name='chen', email='chen@126.com', password='987654')ud = UserDB(name='zhou', email='zhou@163.com', password='456789')ue = UserDB(name='tang', email='tang@lyshark.com', password='158104')uf = UserDB(name='wu', email='wu@gmail.com', password='5623514')ug = UserDB(name='qian', email='qian@gmail.com', password='1543567')uh = UserDB(name='liu', email='liu@lyshark.com', password='867322')ui = UserDB(name='li', email='li@163.com', password='4526342')uj = UserDB(name='sun', email='sun@163.com', 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 eapp.run(debug=True)