SQLAlchemy新增分頁 paginate

2021-08-13 20:52:28 字數 3093 閱讀 1619

from sqlalchemy.orm import  query

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

defpages

(self):

if self.per_page == 0:

pages = 0

else:

pages = int(ceil(self.total / float(self.per_page)))

return pages

defprev

(self, error_out=false):

assert self.query is

notnone, 'a query object is required ' \

'for this method to work'

return self.query.paginate(self.page - 1, self.per_page, error_out)

@property

defprev_num

(self):

ifnot self.has_prev:

return

none

return self.page - 1

@property

defhas_prev

(self):

return self.page > 1

defnext

(self, error_out=false):

assert self.query is

notnone, 'a query object is required ' \

'for this method to work'

return self.query.paginate(self.page + 1, self.per_page, error_out)

@property

defhas_next

(self):

return self.page < self.pages

@property

defnext_num

(self):

ifnot self.has_next:

return

none

return self.page + 1

defiter_pages

(self, left_edge=2, left_current=2,

right_current=5, right_edge=2):

last = 0

for num in xrange(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

defpaginate

(self, page=none, per_page=none, error_out=true):

""" 分頁函式

:param self:

:param page:

:param per_page:

:param error_out:

:return:

"""if request:

if page is

none:

try:

page = int(request.args.get('page', 1))

except (typeerror, valueerror):

if error_out:

abort(404)

page = 1

if per_page is

none:

try:

per_page = int(request.args.get('per_page', 20))

except (typeerror, valueerror):

if error_out:

abort(404)

per_page = 20

else:

if page is

none:

page = 1

if per_page is

none:

per_page = 20

if error_out and page < 1:

abort(404)

items = self.limit(per_page).offset((page - 1) * per_page).all()

ifnot items and page != 1

and error_out:

abort(404)

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#在原查詢類上加上分頁方法

這樣就搞定了,上面的paginate方法和pagination類是從flask-sqlalchemy中複製的,當然也可以通過這個方法為sqlalchemy定製其他的方法。

tp對陣列新增分頁物件

use think paginator driver bootstrap shuju fans 需要分頁的陣列資料 dangqianye input get.page input get.page 1 獲取前端傳過來的分頁值 listrow pagenum 每頁多少條資料 array slice函式...

Django擼部落格之新增分頁功能

django內建了乙個paginator物件,能將給定的list分成指定的數量分頁.貼上官方文件的翻譯 翻譯分頁 原文 有兩個物件需要明確 paginator 分頁物件,用於管理頁面 page 頁面物件,用於代表某一頁 先在檢視中引入 from django.core.paginator impor...

PageHelper的自動新增分頁的問題

如果vo裡有pagenum和pagesize 再加上配置檔案裡supportmethodsarguments true,那麼即使不使用pagehelper.startpage pagenum,pagesize 也會自動分頁。問題就在supportmethodsarguments這個引數,預設是fal...