gdritter repos frony-ritter-designs / 1dcc24c
Fix and abstract out pagination Getty Ritter 4 years ago
2 changed file(s) with 44 addition(s) and 21 deletion(s). Collapse all Expand all
1616 '''
1717 Local module to contain mustache templates
1818 '''
19 renderer = pystache.Renderer(search_dirs='templates')
19 renderer = pystache.Renderer(
20 missing_tags=pystache.common.MissingTags.strict,
21 search_dirs='templates',
22 )
2023
2124 def load_template(name):
2225 with open(f"templates/{name}.mustache") as f:
151154 data = db.get_designs_by_category_and_tag(cat, tag, page)
152155
153156 rs = Templates.design_list(data)
154 print(rs)
155157 return (cat.capitalize(), rs)
156158
157159
55
66 import typing
77
8 PER_PAGE = 16
89
910 def slugify(string):
1011 def process(char):
2122 image: str
2223
2324 def thumb(self):
24 print(self.image)
2525 return self.image[:-4] + '_thumb' + self.image[-4:]
2626
2727
4141
4242 class PageRef(typing.NamedTuple):
4343 page: int
44
45 def __iter__(self):
46 return [self]
4447
4548
4649 class Rendered(typing.NamedTuple):
6669
6770
6871 class Paginated(typing.NamedTuple):
69 next_page: typing.Optional[PageRef]
70 prev_page: typing.Optional[PageRef]
72 next_page: typing.Optional[dict]
73 prev_page: typing.Optional[dict]
7174 last_page: int
7275 contents: typing.List[Design]
76
77 @classmethod
78 def paginate(
79 cls,
80 offset: int,
81 total: int,
82 contents: typing.List[Design],
83 ) -> 'Paginated':
84 last_page = total // PER_PAGE
85 next_page = PageRef(page=offset+1) if offset < last_page else None
86 prev_page = PageRef(page=offset-1) if offset > 0 else None
87 return cls(
88 next_page=next_page,
89 prev_page=prev_page,
90 last_page=last_page,
91 contents=contents,
92 )
7393
7494
7595 class Tag(typing.NamedTuple):
87107
88108 def __init__(self, per_page=16):
89109 self._db = web.database(dbn='sqlite', db='frony.db')
90 self.per_page = per_page
110 self.per_page = PER_PAGE
91111 self.categories = {}
92112 self.photo_num = self.get_max_photo_num() + 1
93113
220240 cat=cat,
221241 offset=offset * self.per_page,
222242 per_page=self.per_page))
223
224 last_page = 10
225 return Paginated(
226 next_page=None,
227 prev_page=None,
228 last_page=last_page,
229 contents=[
230 Design(
231 title=d.title,
232 images=[Image(d.image)],
233 description=d.description,
234 category=d.cat_name,
235 id=d.id)
236 for d in ds],
237 )
243 total = self._db.query(
244 '''select count(*) as c from designs, tags, categories
245 where designs.category = categories.id
246 and categories.name = $cat
247 and tags.tag_name = $tag
248 and designs.id = tags.design_id''',
249 vars=dict(tag=tag, cat=cat))
250 contents = [
251 Design(
252 title=d.title,
253 images=[Image(d.image)],
254 description=d.description,
255 category=d.cat_name,
256 id=d.id)
257 for d in ds]
258 return Paginated.paginate(offset, total[0].c, contents)
238259
239260 def new_design(self):
240261 new_id = self._db.query(