Skip to content

Commit

Permalink
poetry-and-linting: run black+ruff on whole project
Browse files Browse the repository at this point in the history
  • Loading branch information
gardenerik committed Sep 11, 2023
1 parent 5b73e73 commit 72cab4f
Show file tree
Hide file tree
Showing 39 changed files with 735 additions and 471 deletions.
31 changes: 17 additions & 14 deletions candle/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
'''
"""
Project: Candle (New Generation): Candle rewrite from PHP to Python.
Author: Daniel Grohol
'''
"""

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect

from candle.config import Config

login_manager = LoginManager() # keeps session data
login_manager.login_view = 'auth.login'
# login_manager.login_message_category = 'info' # flash message category (not yet implemented)
login_manager.login_view = "auth.login"
# login_manager.login_message_category = 'info'
# ^ flash message category (not yet implemented)

csrf = CSRFProtect() # We need CSRF protection for our AJAX calls. More info: https://stackoverflow.com/questions/31888316/how-to-use-flask-wtforms-csrf-protection-with-ajax
# We need CSRF protection for our AJAX calls.
# More info: https://stackoverflow.com/questions/31888316/how-to-use-flask-wtforms-csrf-protection-with-ajax
csrf = CSRFProtect()
db = SQLAlchemy()
debug_toolbar = DebugToolbarExtension()

Expand All @@ -30,18 +34,17 @@ def create_app(config_class=Config):


def register_blueprints(app):
from candle.api import create_api
from candle.auth.auth import auth
from candle.timetable.timetable import timetable
from candle.common.frontend import common
from candle.groups.frontend import groups
from candle.my_timetable.my_timetable import my_timetable
from candle.panel.panel import panel
from candle.search.search import search

from candle.api import create_api
from candle.common.frontend import common
from candle.rooms.frontend import rooms
from candle.groups.frontend import groups
from candle.search.search import search
from candle.subjects.frontend import subjects
from candle.teachers.frontend import teachers
from candle.timetable.timetable import timetable

app.register_blueprint(auth)
app.register_blueprint(timetable)
Expand All @@ -67,5 +70,5 @@ def init_extensions(app):

app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.jinja_env.add_extension('jinja2.ext.do')
app.jinja_env.add_extension("jinja2.ext.loopcontrols")
app.jinja_env.add_extension("jinja2.ext.do")
9 changes: 4 additions & 5 deletions candle/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ def fn(error):


def create_api():
api = Blueprint('api', __name__, url_prefix="/api")
api = Blueprint("api", __name__, url_prefix="/api")

from candle.teachers.api import teachers
from candle.subjects.api import subjects
from candle.rooms.api import rooms
from candle.groups.api import groups
from candle.rooms.api import rooms
from candle.subjects.api import subjects
from candle.teachers.api import teachers

api.register_blueprint(teachers)
api.register_blueprint(subjects)
Expand All @@ -26,4 +26,3 @@ def create_api():
api.register_error_handler(500, get_error_handler(500, "Server error."))

return api

32 changes: 17 additions & 15 deletions candle/auth/auth.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,37 @@
'''
"""
Project: Candle (New Generation): Candle rewrite from PHP to Python.
Author: Daniel Grohol, FMFI UK
'''
"""

from flask import Blueprint, redirect, request, url_for, flash, current_app
from candle import db
from candle.models import User
from flask_login import login_user, logout_user
from functools import wraps

from flask import Blueprint, current_app, flash, redirect, request, url_for
from flask_login import login_user, logout_user

auth = Blueprint('auth', __name__)
from candle import db
from candle.models import User

auth = Blueprint("auth", __name__)


def require_remote_user(func):
@wraps(func)
def wrapper(*args, **kwargs):
if current_app.config['DEBUG']:
if current_app.config["DEBUG"]:
request.environ.setdefault("REMOTE_USER", "svttest")
else:
if request.environ.get('REMOTE_USER') is None:
flash('User not logged in', 'error')
return redirect(url_for('common.home'))
if request.environ.get("REMOTE_USER") is None:
flash("User not logged in", "error")
return redirect(url_for("common.home"))
return func(*args, **kwargs)

return wrapper


@auth.route('/prihlasit')
@auth.route("/prihlasit")
@require_remote_user
def login():
ais_login = request.environ.get('REMOTE_USER')
ais_login = request.environ.get("REMOTE_USER")
user = User.query.filter_by(login=ais_login).first()
if not user:
# vytvori takeho uzivatela v DB:
Expand All @@ -42,8 +44,8 @@ def login():
return redirect(url_for("common.home"))


@auth.route('/odhlasit')
@auth.route("/odhlasit")
@require_remote_user
def logout():
logout_user()
return redirect(url_for('common.home'))
return redirect(url_for("common.home"))
51 changes: 29 additions & 22 deletions candle/common/frontend.py
Original file line number Diff line number Diff line change
@@ -1,67 +1,74 @@
from flask import Blueprint, render_template, redirect, url_for, request
from flask import Blueprint, redirect, render_template, request, url_for
from flask_login import current_user
from flask_wtf.csrf import CSRFError

from candle import db
from candle.groups.search import search_groups
from candle.models import UserTimetable
from flask_wtf.csrf import CSRFError

from candle.rooms.search import search_rooms
from candle.subjects.search import search_subjects
from candle.teachers.search import search_teachers

common = Blueprint('common', __name__, template_folder="templates",
static_folder='static',
static_url_path='/common/static')
common = Blueprint(
"common",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/common/static",
)


@common.route('/')
@common.route("/")
def home():
if current_user.is_authenticated:
my_timetables = current_user.timetables
# if the user doesn't have any timetable:
if my_timetables.first() is None:
# create a new one:
ut = UserTimetable(name='Rozvrh', user_id=current_user.id)
ut = UserTimetable(name="Rozvrh", user_id=current_user.id)
db.session.add(ut)
db.session.commit()
else:
# select the latest one (with the highest id):
ut = my_timetables.order_by(UserTimetable.id_)[-1]
# redirect to user's timetable view:
return redirect(url_for('my_timetable.show_timetable', id_=ut.id_) )
return redirect(url_for("my_timetable.show_timetable", id_=ut.id_))
else: # user is logged out, show welcome-info:
return render_template('timetable/timetable.html', title='Rozvrh', show_welcome=True)
return render_template(
"timetable/timetable.html", title="Rozvrh", show_welcome=True
)


@common.route('/search/')
@common.route("/search/")
def search():
query = request.args.get("q")
if query:
return render_template("search.html", title="Vyhľadávanie",
subjects=search_subjects(query).limit(20).all(),
groups=search_groups(query).limit(20).all(),
rooms=search_rooms(query).limit(20).all(),
teachers=search_teachers(query).limit(20).all(),
)
return render_template('search.html', title='Vyhľadávanie')
return render_template(
"search.html",
title="Vyhľadávanie",
subjects=search_subjects(query).limit(20).all(),
groups=search_groups(query).limit(20).all(),
rooms=search_rooms(query).limit(20).all(),
teachers=search_teachers(query).limit(20).all(),
)
return render_template("search.html", title="Vyhľadávanie")


@common.app_errorhandler(404)
def error_404(error):
return render_template('errors/404.html'), 404
return render_template("errors/404.html"), 404


@common.app_errorhandler(403)
def error_403(error):
return render_template('errors/403.html'), 403
return render_template("errors/403.html"), 403


@common.app_errorhandler(500)
def error_500(error):
return render_template('errors/500.html'), 500
return render_template("errors/500.html"), 500


@common.app_errorhandler(CSRFError)
def csrf_error(reason):
return render_template('errors/csrf_error.html', reason=reason.description), 400
return render_template("errors/csrf_error.html", reason=reason.description), 400
30 changes: 18 additions & 12 deletions candle/config.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
'''
"""
Project: Candle (New Generation): Candle rewrite from PHP to Python.
Author: Daniel Grohol, FMFI UK
'''
"""

import os
from datetime import date

from dotenv import load_dotenv


# load .env file where environment variables are stored:
basedir = os.path.abspath(os.path.dirname(__file__))
ENV_FILE_PATH = os.path.join(basedir, '../.env')
if os.path.exists(ENV_FILE_PATH) == False:
raise FileNotFoundError('.env file is missing. Check README.md for the instructions how to create one.')
ENV_FILE_PATH = os.path.join(basedir, "../.env")
if os.path.exists(ENV_FILE_PATH) is False:
raise FileNotFoundError(
".env file is missing. Check README.md for the instructions how to create one."
)
load_dotenv(ENV_FILE_PATH)


Expand All @@ -24,15 +25,18 @@ class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get("SQLALCHEMY_DATABASE_URI")
if not SQLALCHEMY_DATABASE_URI:
raise ValueError("""No SQLALCHEMY_DATABASE_URI set for Flask application.
Check README.md for the instructions how to create .env file
and store your SQLALCHEMY_DATABASE_URI there.""")
raise ValueError(
"No SQLALCHEMY_DATABASE_URI set for Flask application. Check README.md for "
"the instructions how to create .env file and store your "
"SQLALCHEMY_DATABASE_URI there."
)

SECRET_KEY = os.environ.get("SECRET_KEY")
if not SECRET_KEY:
raise ValueError("""No SECRET_KEY set for Flask application.
Check README.md for the instructions how to create .env file
and store your SECRET_KEY there.""")
raise ValueError(
"No SECRET_KEY set for Flask application. Check README.md for the "
"instructions how to create .env file and store your SECRET_KEY there."
)

# app.config['SQLALCHEMY_ECHO'] = True # show queries, that runs "in background"
# TODO: real values
Expand All @@ -44,8 +48,10 @@ class Config:
class ProductionConfig(Config):
...


class DevelopmentConfig(Config):
DEBUG = True


class TestingConfig(Config):
DEBUG = True
2 changes: 1 addition & 1 deletion candle/groups/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from candle.groups.search import get_group, search_groups

groups = Blueprint('groups', __name__, url_prefix='/groups')
groups = Blueprint("groups", __name__, url_prefix="/groups")


@groups.route("/")
Expand Down
20 changes: 13 additions & 7 deletions candle/groups/frontend.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@

from typing import Dict
from flask import render_template, Blueprint, request

from candle.groups.search import search_groups, get_group
from flask import Blueprint, render_template, request

from candle.groups.search import get_group, search_groups
from candle.timetable.blueprints.readonly import register_timetable_routes

groups = Blueprint('groups', __name__, template_folder='templates', url_prefix='/groups')
groups = Blueprint(
"groups", __name__, template_folder="templates", url_prefix="/groups"
)


@groups.route('/')
@groups.route("/")
def listing():
"""Show all student groups."""
groups_list = search_groups(request.args.get("q"))
student_groups_dict = get_student_groups_sorted_by_first_letter(groups_list)
title = "Rozvrhy krúžkov"
return render_template('groups/listing.html', student_groups_dict=student_groups_dict,
title=title, web_header=title)
return render_template(
"groups/listing.html",
student_groups_dict=student_groups_dict,
title=title,
web_header=title,
)


register_timetable_routes(groups, get_group)
Expand Down
12 changes: 7 additions & 5 deletions candle/groups/models.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
from candle import db
from candle.models import SchoolTimetable

student_group_lessons = db.Table('student_group_lessons',
db.Column('student_group_id', db.Integer, db.ForeignKey('student_group.id')),
db.Column('lesson_id', db.Integer, db.ForeignKey('lesson.id')))
student_group_lessons = db.Table(
"student_group_lessons",
db.Column("student_group_id", db.Integer, db.ForeignKey("student_group.id")),
db.Column("lesson_id", db.Integer, db.ForeignKey("lesson.id")),
)


class StudentGroup(SchoolTimetable):
id_ = db.Column('id', db.Integer, primary_key=True)
id_ = db.Column("id", db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
lessons = db.relationship('Lesson', secondary=student_group_lessons, lazy='dynamic')
lessons = db.relationship("Lesson", secondary=student_group_lessons, lazy="dynamic")

def __str__(self):
return self.name
Expand Down
9 changes: 6 additions & 3 deletions candle/groups/search.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from candle.groups.models import StudentGroup
from flask_sqlalchemy.query import Query

from candle.groups.models import StudentGroup


def search_groups(query: str|None) -> Query:
def search_groups(query: str | None) -> Query:
groups = StudentGroup.query.order_by(StudentGroup.name)
if query:
groups = groups.filter(StudentGroup.name.ilike(f"%{query}%"))
return groups


def get_group(slug: str) -> StudentGroup:
return StudentGroup.query.filter((StudentGroup.id_==slug) | (StudentGroup.name==slug)).first_or_404()
return StudentGroup.query.filter(
(StudentGroup.id_ == slug) | (StudentGroup.name == slug)
).first_or_404()
Loading

0 comments on commit 72cab4f

Please sign in to comment.