Skip to content

Instantly share code, notes, and snippets.

@joeynimu
Last active June 9, 2016 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeynimu/3e81008a2208872bc4ac4d18d93bdf97 to your computer and use it in GitHub Desktop.
Save joeynimu/3e81008a2208872bc4ac4d18d93bdf97 to your computer and use it in GitHub Desktop.
A small class that accepts an object/data and creates a dynamic pagination.
class Paginate(object):
result_size = 0
current_page = 0
def __init__(self, results, page, limit=5):
self.result_size = len(results)
self.current_page = page
self.results = results
self.limit = limit
def has_next(self):
return bool(((self.current_page + 1) * self.limit) < self.result_size)
def has_prev(self):
return self.current_page > 0
@property
def pages(self):
return int(ceil(self.result_size / float(self.limit)))
@property
def last_index(self):
return (self.current_page + 1) * self.limit
@property
def first_index(self):
return self.last_index - self.limit
def get_current_page_results(self):
if self.first_index > self.result_size:
self.current_page = 0
if self.last_index > self.result_size:
return self.results[self.first_index:]
else:
return self.results[self.first_index:self.last_index]
#sample usage
@app.route('/search')
def search():
app.logger.debug('Search page called.')
# TODO: not sure about the below code :-)
page = int(request.args.get('page', 0))
results = search_api.get_search_results()
pagination = Paginate(results, page)
return render_template(pagination=pagination)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment