Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Poetry and linting #25

Merged
merged 6 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: pre-commit check

on:
pull_request:
push:
branches:
- master

jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- uses: pre-commit/action@v3.0.0
12 changes: 12 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.288'
hooks:
- id: ruff
args: [ --fix, --exit-non-zero-on-fix ]

- repo: https://github.com/psf/black
rev: 23.9.1
hooks:
- id: black
language_version: python3.11
10 changes: 6 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.10-slim-bullseye
FROM python:3.11-slim-bullseye

WORKDIR /app
RUN useradd --create-home appuser
Expand All @@ -15,9 +15,11 @@ RUN export DEBIAN_FRONTEND=noninteractive \

USER appuser

COPY ./requirements ./requirements
RUN pip install -r requirements/requirements.txt
RUN pip install poetry
COPY poetry.lock .
COPY pyproject.toml .
RUN poetry install

COPY ./candle ./candle

CMD ["flask", "run", "--host=0.0.0.0"]
CMD ["poetry", "run", "flask", "run", "--host=0.0.0.0"]
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
Loading
Loading