1 class Pagination(object): 2 def __init__(self, totalCount, currentPage, perPageItemNum=20, maxPageNum=7): 3 # 数据总个数 4 self.total_count = totalCount 5 # 但前页 6 try: 7 v = int(currentPage) 8 if v <= 0: 9 v = 1 10 self.current_page = v 11 except Exception as e: 12 self.current_page = 1 13 # 每页显示的行数 14 self.per_page_item_num = perPageItemNum 15 # 最多显示页面 16 self.max_page_num = maxPageNum 17 18 def start(self): 19 return (self.current_page-1) * self.per_page_item_num 20 21 def end(self): 22 return self.current_page * self.per_page_item_num 23 @property 24 def num_pages(self): 25 # 总页数 26 a, b = divmod(self.total_count, self.per_page_item_num) 27 if b == 0: 28 return a 29 return a + 1 30 31 def pager_num_range(self): 32 if self.num_pages < self.max_page_num: 33 return range(1, self.num_pages + 1) 34 # 总页数特别多 35 part = int(self.max_page_num / 2) 36 if self.current_page <= part: 37 return range(1, self.max_page_num + 1) 38 if (self.current_page + part) > self.num_pages: 39 return range(self.num_pages - self.max_page_num + 1, self.num_pages + 1) 40 return range(self.current_page-part, self.current_page + part + 1) 41 42 def page_str(self): 43 page_list = [] 44 # 首页 45 page_first = '<li><a href="/index2.html?p=1">首页</a></li>' 46 page_list.append(page_first) 47 if self.current_page == 1: 48 prev = '<li><a href="#">上一页</a></li>' 49 else: 50 prev = '<li><a href="/index2.html?p=%s">上一页</a></li>' % (self.current_page - 1,) 51 page_list.append(prev) 52 for i in self.pager_num_range(): 53 if i == self.current_page: 54 temp = '<li class="active"><a href="/index2.html?p=%s">%s</a></li>' % (i, i) 55 else: 56 temp = '<li><a href="/index2.html?p=%s">%s</a></li>' % (i, i) 57 page_list.append(temp) 58 # 如果当前页等于最后一页 59 if self.current_page == self.num_pages: 60 nex = '<li><a href="#">下一页</a>' 61 else: 62 nex = '<li><a href="/index2.html?p=%s">下一页</a></li>' % (self.current_page + 1,) 63 page_list.append(nex) 64 # 尾页 65 page_last = '<li><a href="/index2.html?p=%s">尾页</a></li>' % (self.num_pages,) 66 page_list.append(page_last) 67 return ''.join(page_list)