分页
动态计算分页按钮
# coding=utf-8
import math
class Page:
def __init__(self, data_count, page_size=5, pre_page_num=10):
"""
分页
:param data_count: 数据总量
:param page_size: 分页展示数量 => < [1] 2 3 4 5 >
:param pre_page_num: 每页展示的数量
"""
self.min_page = 1
self.page_size = page_size
self.data_count = data_count if data_count > 0 else 0
self.pre_page_num = pre_page_num
self.current_page = 1
self.max_page = math.ceil(self.data_count / self.pre_page_num)
# 获取数据取值边界
def get_data_border(self, current_page):
"""
:type current_page: 当前页码
"""
self.current_page = current_page
# 判断pag_num是否越界
if self.current_page > self.max_page:
self.current_page = self.max_page
if self.current_page <= self.min_page:
self.current_page = self.min_page
self.data_start = (self.current_page - 1) * self.pre_page_num
self.data_end = self.current_page * self.pre_page_num
return self.data_start, self.data_end
# 获取分页的开始位置和结束位置
def get_page(self, current_page=None):
if current_page:
self.current_page = current_page
if self.max_page <= self.page_size:
self.start_page = self.min_page
self.end_page = self.max_page
if self.end_page < self.start_page:
self.end_page = self.start_page
return self.start_page, self.end_page, self.page_size, self.pre_page_num
half_show = math.floor(self.page_size // 2)
start_page = self.current_page - half_show
end_page = self.current_page + half_show
# 判断边界
if start_page <= self.min_page:
start_page = self.min_page
end_page = start_page + self.page_size - 1
if end_page >= self.max_page:
end_page = self.max_page
start_page = end_page - self.page_size + 1
self.start_page = start_page
self.end_page = end_page
return self.start_page, self.end_page, self.page_size, self.pre_page_num
def reset_data_count(self, data_count):
self.data_count = data_count if data_count > 0 else 0
# 返回一个range 对象
@property
def page_num_range(self):
return range(self.start_page, self.end_page + 1)