结合mysql数据库查询,实现分页效果
@user.route("/user_list",methods=['POST','GET'])
def user_list():
p = g.args.get("p", '') #页数
show_shouye_status = 0 #显示首页状态
if p =='':
p=1
else:
p=int(p)
if p > 1:
show_shouye_status = 1
mdb = db_session()
limit_start = (int(p)-1)*10#起始
sql ="select * from page_text limit {0},10".format(limit_start)
user_list=mdb.getMany(sql)
sql="select count(id) as total from page_text"
count = mdb.getOne(sql)['total'] #总记录
total = int(math.ceil(count/10.0)) #总页数
dic = get_page(total,p)
datas={
'user_list':user_list,
'p': int(p),
'total': total,
'show_shouye_status': show_shouye_status,
'dic_list': dic
}
return render_template("user_list.html",datas=datas)
其中get_page为封装的方法:
def get_page(total,p):
show_page = 5 # 显示的页码数
pageoffset = 2 # 偏移量
start = 1 #分页条开始
end = total #分页条结束
if total > show_page:
if p > pageoffset:
start = p - pageoffset
if total > p + pageoffset:
end = p + pageoffset
else:
end = total
else:
start = 1
if total > show_page:
end = show_page
else:
end = total
if p + pageoffset > total:
start = start - (p + pageoffset - end)
#用于模版中循环
dic = range(start, end + 1)
return dic
如果这里需要进行前端模板的拼接的话,可以需要以下代码(bootstrap)
<ul class="pagination"> {% if datas.show_shouye_status==1%} <li class=''><a href='/user/user_list?p=1'>首页</a></li> <li class=''><a href='/user/user_list?p={{datas.p-1}}'>上一页</a></li> {%endif%} {% for dic in datas.dic_list %} {% if dic==datas.p%} <li class="active"><a href="/user/user_list?p={{dic}}">{{dic}}</a></li> {%else%} <li><a href="/user/user_list?p={{dic}}">{{dic}}</a></li> {%endif%} {%endfor%} {% if datas.p < datas.total%} <li class=''><a href='/user/user_list?p={{datas.p+1}}'>下一页</a></li> <li class=''><a href='/user/user_list?p={{datas.total}}'>尾页</a></li> {%endif%} 共{{datas.total}}页 </ul>
bootstrap样式 http://www.runoob.com/bootstrap/bootstrap-pagination.html
如果是返回给APP端的话,直接返回data数据就可以了。
更多博客请访问:
https://blog.csdn.net/xudailong_blog/article/details/78762262