在web开发中,分页是必不可少的功能,这里通过实例来了解下简单的分页功能。
1.test.py文件
@web_blue.route('/')
def stu_psge():
# 获取page参数 默认为1
page = int(request.args.get('page',1))
# 获取每页显示数据条数默认为2
per_page = int(request.args.get('perpage',2))
# 从数据库查询数据
paginates = Test.query.order_by('id').paginate(page,per_page,error_out=False)
stus = paginates.items
# totalpage为总页面数
totalpage = math.ceil(paginates.total/per_page)
return render_template('test.html',paginate = paginates,stus = stus,totalpage = totalpage)
注意:paginates是flask_sqlalchemy.Pagination类型。
math.celi表示对页面数向上取整,需要引入math模块。
2.test.html文件
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<br>
<br >
<h1>所有人员</h1>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>操作</th>
</tr>
{% for stus in stus %}
<tr>
<td>{{ stus.id }}</td>
<td>{{ stus.title }}</td>
<td>
<a href="{{ url_for('web.dele',id=stus.id) }}">删除</a>
<a href="{{ url_for('web.mysqlmodify',uid=stus.id,uname=stus.title) }}">修改</a>
</td>
</tr>
{% endfor %}
</table>
<br>
总页数{{ (totalpage) }}
<br>
总共有{{ paginate.total }}调数据
<br>
当前页数:{{ paginate.page }}
<br>
当前的页数:{{ paginate.page }}
<br>
{#如果存在上一页#}
{% if paginate.has_prev %}
<a href="/?page={{ paginate.prev_num }}">上一页:</a>
{% endif %}
{% for i in paginate.iter_pages() %}
<a href="/?page={{ i }}">{{ i }}</a>
{% endfor %}
{#如果存在下一页#}
{% if paginate.has_next %}
<a href="/?page={{ paginate.next_num }}">下一页:</a>
{% endif %}
<br>
</html>
3.test数据表
4.浏览器运行结果。
点击下一页: