1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from math
import ceil
, floor
20 from itertools
import izip
, count
23 PAGINATION_DEFAULT_PER_PAGE
= 30
26 class Pagination(object):
28 Pagination class for mongodb queries.
30 Initialization through __init__(self, cursor, page=1, per_page=2),
31 get actual data slice through __call__().
34 def __init__(self
, page
, cursor
, per_page
=PAGINATION_DEFAULT_PER_PAGE
,
37 Initializes Pagination
40 - page: requested page
41 - per_page: number of objects per page
43 - jump_to_id: ObjectId, sets the page to the page containing the
44 object with _id == jump_to_id.
47 self
.per_page
= per_page
49 self
.total_count
= self
.cursor
.count()
53 cursor
= copy
.copy(self
.cursor
)
55 for (doc
, increment
) in izip(cursor
, count(0)):
56 if doc
._id
== jump_to_id
:
57 self
.page
= 1 + int(floor(increment
/ self
.per_page
))
59 self
.active_id
= jump_to_id
65 Returns slice of objects for the requested page
67 return self
.cursor
.skip(
68 (self
.page
- 1) * self
.per_page
).limit(self
.per_page
)
72 return int(ceil(self
.total_count
/ float(self
.per_page
)))
80 return self
.page
< self
.pages
82 def iter_pages(self
, left_edge
=2, left_current
=2,
83 right_current
=5, right_edge
=2):
85 for num
in xrange(1, self
.pages
+ 1):
86 if num
<= left_edge
or \
87 (num
> self
.page
- left_current
- 1 and \
88 num
< self
.page
+ right_current
) or \
89 num
> self
.pages
- right_edge
:
95 def get_page_url_explicit(self
, base_url
, get_params
, page_no
):
97 Get a page url by adding a page= parameter to the base url
99 new_get_params
= copy
.copy(get_params
or {})
100 new_get_params
['page'] = page_no
102 base_url
, urllib
.urlencode(new_get_params
))
104 def get_page_url(self
, request
, page_no
):
106 Get a new page url based of the request, and the new page number.
108 This is a nice wrapper around get_page_url_explicit()
110 return self
.get_page_url_explicit(
111 request
.full_path
, request
.GET
, page_no
)