1.分页操作跟随大神视频逐步讲解自己写出来。
大致思路:
1.定义好 当前页,每页显示行数,数据总行数,一共显示的页数
2.创建page_list列表 首页和最后一页分别加入到列表的最前和最后。
3.用if判断语句来嵌套判定各种条件。
4.重要的是前后的判断,如当前显示的页数小于显示页数的一半等。
以下是代码,贴上以备不时之需。
class PageInfo(object):
def __init__(self,current_page,all_count,per_page,show_page=11):
"""
:param current_page: 当前页
:param all_count: 数据总行数
:param per_page: 每页显示数据数
:param show_page: 一共显示的页数
"""
try:
self.current_page=int(current_page)
except Exception as e:
self.current_page=1
##如果当页码不为字符串则当前页码返回第一页
self.per_page=per_page
a,b=divmod(all_count,per_page)
##用divmod计算一共多少页面
if b:
a=a+1
self.all_page=a
self.show_page=show_page
def strat(self):
return (self.current_page-1)*self.per_page
def end(self):
return self.current_page*self.per_page
def pager(self):
#v='<a href=/app01/customs.html?page=19>19</a>'
#以字符串形式传入前端 不过需要加|safe
half=int((self.show_page-1)/2)
##用总的显示页面数量的一半表示前后各有多少个,为了前后数量一致总数为单数。
if self.all_page<self.show_page:
begin=1
stop=self.all_page
##如果数据总数小于显示页面数 永远从第一页开始,总页数为最大页数
else:
if self.current_page<half:
begin=1
stop=self.show_page+1
##当前页小于总页数一半
else:
if self.current_page+half>self.all_page:
begin=self.all_page-self.show_page+1
stop=self.all_page+1
else:
begin =self.current_page-half
stop = self.current_page+half+1
# begin=self.current_page-half
# #起始位置
# stop=self.current_page+half+1
# #末尾位置
page_list=[]
frist='<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=1>首页</a>'
page_list.append(frist)
if self.current_page <=1:
prev = '<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=#>上一页</a>'
else:
prev='<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=%s>上一页</a>' % (self.current_page-1)
page_list.append(prev)
##创建一个列表来列出所有的页数
for i in range(begin,stop):
##循环所有的页面
if i == self.current_page:
temp = '<a style ="display:inline-block;background-color:red;margin:3px;padding:3px"href=/app01/customs.html?page=%s>%s</a>' % (
self.current_page, self.current_page)
##判断是否为当前页,如果为当前页就显示为底色为红色
else:
temp ='<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=%s>%s</a>'%(i,i)
#调整了一下样式
page_list.append(temp)
if self.current_page >=self.all_page:
nex = '<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=#>下一页</a>'
else:
nex = '<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=%s>下一页</a>' % (
self.current_page + 1)
page_list.append(nex)
last=prev = '<a style ="display:inline-block;margin:3px;padding:3px"href=/app01/customs.html?page=%s>尾页</a>'%(self.all_page)
page_list.append(last)
return ''.join(page_list)
##用.join 方法temp字符串拼接起来