Pagination

I hate math
This commit is contained in:
Michał Gdula 2023-04-06 18:42:04 +00:00
parent f33842ead3
commit a46192566f
6 changed files with 108 additions and 15 deletions

View file

@ -1,6 +1,8 @@
"""
Onlylegs - Image View
"""
from math import ceil
from flask import Blueprint, abort, render_template, url_for
from sqlalchemy.orm import sessionmaker
@ -55,5 +57,26 @@ def image(image_id):
next_url = url_for('image.image', image_id=next_url[0])
if prev_url:
prev_url = url_for('image.image', image_id=prev_url[0])
# Yoink all the images in the database
total_images = (db_session.query(db.Posts.id)
.order_by(db.Posts.id.desc())
.all())
limit = 100
return render_template('image.html', image=image, next_url=next_url, prev_url=prev_url)
# If the number of items is less than the limit, no point of calculating the page
if len(total_images) <= limit:
return_page = 1
else:
# How many pages should there be
for i in range(ceil(len(total_images) / limit)):
# Slice the list of IDs into chunks of the limit
for j in total_images[i * limit:(i + 1) * limit]:
# Is our image in this chunk?
if image_id in j:
return_page = i + 1
break
return render_template('image.html', image=image, next_url=next_url,
prev_url=prev_url, return_page=return_page)

View file

@ -1,6 +1,8 @@
"""
Onlylegs Gallery - Index view
"""
from math import ceil
from flask import Blueprint, render_template, request
from werkzeug.exceptions import abort
@ -18,13 +20,30 @@ def index():
"""
Home page of the website, shows the feed of the latest images
"""
images = db_session.query(db.Posts.filename,
db.Posts.alt,
db.Posts.colours,
db.Posts.created_at,
db.Posts.id).order_by(db.Posts.id.desc()).all()
# meme
if request.args.get('coffee') == 'please':
abort(418)
# pagination, defaults to page 1 if no page is specified
page = request.args.get('page', default=1, type=int)
limit = 100
# get the total number of images in the database
# calculate the total number of pages, and make sure the page number is valid
total_images = db_session.query(db.Posts.id).count()
pages = ceil(max(total_images, limit) / limit)
if page > pages:
abort(404, 'You have reached the far and beyond, ' +
'but you will not find your answers here.')
# get the images for the current page
images = (db_session.query(db.Posts.filename, db.Posts.alt, db.Posts.colours,
db.Posts.created_at, db.Posts.id)
.order_by(db.Posts.id.desc())
.offset((page - 1) * limit)
.limit(limit)
.all())
return render_template('index.html', images=images)
return render_template('index.html', images=images,
total_images=total_images,
pages=pages, page=page)