open-law/app/views/home.py

79 lines
2.4 KiB
Python
Raw Normal View History

2023-04-21 11:40:20 +00:00
from flask import (
Blueprint,
render_template,
2023-06-13 14:03:36 +00:00
request,
2023-04-21 11:40:20 +00:00
)
2023-06-14 14:17:43 +00:00
from sqlalchemy import and_, func
2023-05-12 06:55:10 +00:00
from app import models as m, db
2023-05-26 13:56:04 +00:00
from app.logger import log
2023-06-14 14:17:43 +00:00
from app.controllers.sorting import sort_by
2023-05-26 13:56:04 +00:00
2023-04-21 11:40:20 +00:00
bp = Blueprint("home", __name__, url_prefix="/home")
@bp.route("/", methods=["GET"])
def get_all():
2023-06-13 14:03:36 +00:00
sort = request.args.get("sort")
2023-06-14 08:09:02 +00:00
interpretations = (
db.session.query(
m.Interpretation,
2023-06-14 14:17:43 +00:00
m.Interpretation.score.label("score"),
m.Interpretation.created_at.label("created_at"),
2023-06-14 08:09:02 +00:00
func.count(m.Comment.interpretation_id).label("comments_count"),
2023-05-12 06:55:10 +00:00
)
2023-06-14 14:17:43 +00:00
.join(
m.Comment,
2023-06-14 08:09:02 +00:00
and_(
2023-06-14 14:17:43 +00:00
m.Comment.interpretation_id == m.Interpretation.id,
m.Comment.is_deleted == False, # noqa: E712
),
isouter=True,
)
.filter(
m.Interpretation.is_deleted == False, # noqa: E712
2023-06-14 08:09:02 +00:00
)
.group_by(m.Interpretation.id)
2023-05-12 06:55:10 +00:00
)
2023-06-14 14:17:43 +00:00
pagination, interpretations = sort_by(interpretations, sort)
2023-06-13 14:03:36 +00:00
2023-04-21 11:40:20 +00:00
return render_template(
"home/index.html",
2023-06-14 08:09:02 +00:00
interpretations=interpretations,
2023-06-13 14:03:36 +00:00
page=pagination,
)
@bp.route("/explore_books", methods=["GET"])
def explore_books():
log(log.INFO, "Create query for home page for books")
2023-06-14 14:17:43 +00:00
sort = request.args.get("sort")
2023-06-13 14:03:36 +00:00
2023-06-14 14:17:43 +00:00
books: m.Book = (
db.session.query(
m.Book,
m.Book.created_at.label("created_at"),
func.count(m.Interpretation.id).label("interpretations_count"),
func.count(m.BookStar.id).label("stars_count"),
)
.join(m.BookStar, m.BookStar.book_id == m.Book.id, full=True)
.join(m.BookVersion, m.BookVersion.book_id == m.Book.id)
.join(m.Section, m.BookVersion.id == m.Section.version_id, full=True)
.join(m.Interpretation, m.Interpretation.section_id == m.Section.id, full=True)
.filter(
m.Book.is_deleted == False, # noqa: E712
m.BookStar.is_deleted == False, # noqa: E712
m.BookVersion.is_deleted == False, # noqa: E712
m.Section.is_deleted == False, # noqa: E712
m.Interpretation.is_deleted == False, # noqa: E712
)
.group_by(m.Book.id)
)
2023-06-13 14:03:36 +00:00
log(log.INFO, "Creating pagination for books")
2023-06-14 14:17:43 +00:00
pagination, books = sort_by(books, sort)
2023-06-13 14:03:36 +00:00
return render_template(
"home/explore_books.html",
2023-06-14 14:17:43 +00:00
books=books,
2023-06-13 14:03:36 +00:00
page=pagination,
2023-04-21 11:40:20 +00:00
)