Python: Google App Engine (GAE) Paginator Class

时间:2021-12-15 23:16:06
 1 """
 2 Usage: 
 3     query = User.gql('order by lastname')
 4     pager = Paginator(query,url="/userlist/",pagesize=5)
 5     results,pager = pager.fetch(offset)
 6 	
 7 """
 8 class Paginator(object):
 9   def __init__(self,query=None,pagesize=5,url=None):
10     self.query = query
11     self.pagesize = pagesize
12     if not url.endswith('/'):
13       self.url = url + '/'
14     else:
15       self.url = url
16
17   def fetch(self,offset):
18     results =self.query.fetch(100,offset)
19     output = self.create_links(offset,len(results))
20     return (results[:self.pagesize],output)
21
22   def create_links(self,offset,count):
23     num_links = 5
24     if count % self.pagesize ==0 :
25       num_pages = count/self.pagesize -1
26     else:
27       num_pages = count/self.pagesize
28
29     cur_page = offset/self.pagesize + 1
30     start_page = 1
31     end_page = cur_page + num_links
32
33     if cur_page - num_links >0:
34       start_page = cur_page - num_links + 1
35     if num_pages < num_links:
36       end_page = cur_page + num_pages
37
38     if end_page==1:
39       return ''
40     links = []
41
42     for i in range(start_page,end_page+1):
43       links_item = {}
44       links_item['index'] = i
45       links_item['offset'] = (i-1) * self.pagesize
46       links.append(links_item)
47
48     pagelinks = {}
49     pagelinks['item'] = links
50     pagelinks['cur_page'] = cur_page
51     if cur_page>1:
52       pagelinks['prev'] = offset - self.pagesize
53     else:
54       pagelinks['prev'] = None
55
56     if cur_page < end_page:
57       pagelinks['next'] = offset + self.pagesize
58     else:
59       pagelinks['next'] = None
60
61     output = '';
62     if pagelinks['prev'] is not None:
63       output += '<a href="%s%s">上一页</a> ' % (self.url,pagelinks['prev'])
64     for i in pagelinks['item']:
65       if i['index'] != pagelinks['cur_page']:
66         output += '<a href="%s%s">%s</a> ' % (self.url,i['offset'],i['index'])
67       else:
68         output += ' %s ' % (i['index'])
69     if pagelinks['next'] is not None:
70       output += '<a href="%s%s">下一页</a> ' % (self.url,pagelinks['next'])
71     return output