python-gallery/onlylegs/views/index.py

52 lines
1.5 KiB
Python
Raw Normal View History

2023-04-06 16:22:56 +00:00
"""
Onlylegs Gallery - Index view
"""
2023-04-06 18:42:04 +00:00
from math import ceil
2023-04-07 09:18:03 +00:00
from flask import Blueprint, render_template, request, current_app
2023-04-06 16:22:56 +00:00
from werkzeug.exceptions import abort
2023-08-04 17:34:08 +00:00
from onlylegs.models import Pictures, Users
2023-04-06 16:22:56 +00:00
2023-04-07 12:35:30 +00:00
blueprint = Blueprint("gallery", __name__)
2023-04-06 16:22:56 +00:00
2023-04-07 12:35:30 +00:00
@blueprint.route("/")
2023-04-06 16:22:56 +00:00
def index():
"""
Home page of the website, shows the feed of the latest images
"""
2023-04-06 18:42:04 +00:00
# pagination, defaults to page 1 if no page is specified
2023-04-07 12:35:30 +00:00
page = request.args.get("page", default=1, type=int)
limit = current_app.config["UPLOAD_CONF"]["max-load"]
2023-04-06 18:42:04 +00:00
# get the total number of images in the database
# calculate the total number of pages, and make sure the page number is valid
2023-08-04 17:34:08 +00:00
total_images = Pictures.query.with_entities(Pictures.id).count()
2023-04-06 18:42:04 +00:00
pages = ceil(max(total_images, limit) / limit)
if page > pages:
2023-08-04 17:34:08 +00:00
return abort(
2023-04-07 12:35:30 +00:00
404,
2023-08-04 17:34:08 +00:00
"You have reached the far and beyond, but you will not find your answers here.",
2023-04-07 12:35:30 +00:00
)
2023-04-06 18:42:04 +00:00
# get the images for the current page
2023-04-07 12:35:30 +00:00
images = (
2023-08-04 17:34:08 +00:00
Pictures.query.with_entities(
Pictures.filename,
Pictures.alt,
Pictures.colours,
Pictures.created_at,
Pictures.id,
Users.username,
2023-04-12 15:18:13 +00:00
)
2023-08-04 17:34:08 +00:00
.join(Users)
.order_by(Pictures.id.desc())
2023-04-07 12:35:30 +00:00
.offset((page - 1) * limit)
.limit(limit)
.all()
)
return render_template(
"index.html", images=images, total_images=total_images, pages=pages, page=page
)