非flask扩展实现sqlalchemy的paginate分页

日常笔记 16 字 433 阅
class Pagination(object):
"""
分页对象
"""

def __init__(self, query, page, per_page, total, items):
    self.query = query
    self.page = page
    self.per_page = per_page
    self.total = total
    self.items = items

@property
def pages(self):
    if self.per_page == 0:
        pages = 0
    else:
        pages = int(ceil(self.total / float(self.per_page)))
    return pages

def prev(self, error_out=False):
    assert self.query is not None, 'a query object is required ' \
                                   'for this method to work'
    return self.query.paginate(self.page - 1, self.per_page, error_out)

@property
def prev_num(self):
    if not self.has_prev:
        return None
    return self.page - 1

@property
def has_prev(self):
    return self.page > 1

def next(self, error_out=False):
    assert self.query is not None, 'a query object is required ' \
                                   'for this method to work'
    return self.query.paginate(self.page + 1, self.per_page, error_out)

@property
def has_next(self):
    return self.page < self.pages

@property
def next_num(self):
    if not self.has_next:
        return None
    return self.page + 1

def iter_pages(self, left_edge=2, left_current=2,
               right_current=5, right_edge=2):
    last = 0
    for num in range(1, self.pages + 1):
        if num <= left_edge or \
                (num > self.page - left_current - 1 and \
                 num < self.page + right_current) or \
                num > self.pages - right_edge:
            if last + 1 != num:
                yield None
            yield num
            last = num
def paginate(self, page=None, per_page=None, error_out=True):
    items = self.limit(per_page).offset((page - 1) * per_page).all()

    if not items and page != 1 and error_out:
        return

    if page == 1 and len(items) < per_page:
        total = len(items)
    else:
        total = self.order_by(None).count()

    return Pagination(self, page, per_page, total, items)
Query.paginate = paginate  # 在原查询类上加上分页方法
EOF
发表评论 (暂无评论)
OωO
开启隐私评论,您的评论仅作者和评论双方可见