一个SSDB 的分页方法

pylist 232

拿一个读书列表来做例子:

handler

class BookListPage(BaseHandler):
    @authenticated
    def get(self):
        score_info = {
            'prev_score': self.get_argument('prev_score', ''),  # 上一页 key_score
            'cur_score': self.get_argument('cur_score', ''),  # 当前页 key_score
        }
        self.echo('admin_book_list.html', {
            'title': '最近添加的书籍',
            'score_info': score_info,
            'book_page_info': BookModel.get_new_book_page(score_info['cur_score'], 2)
        }, layout='_admin_layout.html')

model

class BookModel(object):
    @staticmethod
    def get_new_book_page(score_start, limit=10):
        if score_start:
            score_start = int(score_start)
        book_size = db.zsize('book_add_time')
        items = []
        new_score_start = ''
        if book_size:
            book_id_vs = db.zrscan('book_add_time', '', score_start, '', limit+1)
            book_ids = book_id_vs.keys()
            book_vs = db.hmget('book_info', *book_ids)
            for bid in book_ids:
                book = json.loads(book_vs[bid])
                items.append(book)
                new_score_start = book['add_time']
        return {'items': items[:limit], 'has_next': 1 if len(items) == limit+1 else 0, 'score_start': new_score_start}

html

<nav>
    <ul class="pager">
      <?py if score_info['cur_score']: ?>
      <li class="previous">
        [← Newer](/admin/book/list?cur_score=#{score_info['prev_score']})
      </li>
        <?py #endif ?>
        <?py if book_page_info['has_next']: ?>
      <li class="next">
        [Older →](/admin/book/list?cur_score=#{book_page_info['score_start']}&prev_score=#{score_info['cur_score']})
      </li>
      <?py #endif ?>
    </ul>
</nav>
登录发表评论

桂公网安备 45122402000014号