Merge pull request #152 from SamR1/minor-fixes

Fixes and improvements
This commit is contained in:
Sam 2022-02-13 15:27:41 +01:00 committed by GitHub
commit 165b828889
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 40 additions and 35 deletions

View File

@ -3,6 +3,7 @@
# Application # Application
export FLASK_ENV=development export FLASK_ENV=development
export FLASK_APP=fittrackee/__main__.py export FLASK_APP=fittrackee/__main__.py
export FLASK_SKIP_DOTENV=1
export APP_SETTINGS=fittrackee.config.DevelopmentConfig export APP_SETTINGS=fittrackee.config.DevelopmentConfig
export APP_SECRET_KEY='just for test' export APP_SECRET_KEY='just for test'
# export APP_WORKERS= # export APP_WORKERS=

View File

@ -3,6 +3,7 @@
# Application # Application
# export FLASK_APP=fittrackee # export FLASK_APP=fittrackee
export FLASK_SKIP_DOTENV=1
# export HOST= # export HOST=
# export PORT= # export PORT=
# export APP_SETTINGS=fittrackee.config.ProductionConfig # export APP_SETTINGS=fittrackee.config.ProductionConfig

View File

@ -162,7 +162,7 @@ serve-python-dev:
$(FLASK) run --with-threads -h $(HOST) -p $(PORT) --cert=adhoc $(FLASK) run --with-threads -h $(HOST) -p $(PORT) --cert=adhoc
set-admin: set-admin:
$(FLASK) set-admin $(USERNAME) $(FLASK) users set-admin $(USERNAME)
test-e2e: init-db test-e2e: init-db
$(PYTEST) e2e --driver firefox $(PYTEST_ARGS) $(PYTEST) e2e --driver firefox $(PYTEST_ARGS)

View File

@ -4,4 +4,4 @@ cd /usr/src/app
source .env.docker source .env.docker
flask set-admin $1 flask users set-admin $1

View File

@ -1,5 +1,6 @@
import logging import logging
import os import os
import shutil
from importlib import import_module, reload from importlib import import_module, reload
from typing import Any from typing import Any
@ -128,4 +129,17 @@ def create_app() -> Flask:
else: else:
return render_template('index.html') return render_template('index.html')
@app.cli.command('drop-db')
def drop_db() -> None:
"""Empty database and delete uploaded files for dev environments."""
if app_settings == 'fittrackee.config.ProductionConfig':
print('This is a production server, aborting!')
return
db.engine.execute("DROP TABLE IF EXISTS alembic_version;")
db.drop_all()
db.session.commit()
print('Database dropped.')
shutil.rmtree(app.config['UPLOAD_FOLDER'], ignore_errors=True)
print('Uploaded files deleted.')
return app return app

View File

@ -1,25 +1,19 @@
# source for StandaloneApplication class: # source for StandaloneApplication class:
# http://docs.gunicorn.org/en/stable/custom.html # http://docs.gunicorn.org/en/stable/custom.html
import os import os
import shutil
from typing import Dict, Optional from typing import Dict, Optional
import click
import gunicorn.app.base import gunicorn.app.base
from flask import Flask from flask import Flask
from flask_dramatiq import worker
from flask_migrate import upgrade from flask_migrate import upgrade
from fittrackee import create_app, db from fittrackee import create_app
from fittrackee.users.exceptions import UserNotFoundException
from fittrackee.users.utils import set_admin_rights
HOST = os.getenv('HOST', '0.0.0.0') HOST = os.getenv('HOST', '0.0.0.0')
PORT = os.getenv('PORT', '5000') PORT = os.getenv('PORT', '5000')
WORKERS = os.getenv('APP_WORKERS', 1) WORKERS = os.getenv('APP_WORKERS', 1)
BASEDIR = os.path.abspath(os.path.dirname(__file__)) BASEDIR = os.path.abspath(os.path.dirname(__file__))
app = create_app() app = create_app()
dramatiq_worker = worker
class StandaloneApplication(gunicorn.app.base.BaseApplication): class StandaloneApplication(gunicorn.app.base.BaseApplication):
@ -48,28 +42,6 @@ def upgrade_db() -> None:
upgrade(directory=BASEDIR + '/migrations') upgrade(directory=BASEDIR + '/migrations')
@app.cli.command('drop-db')
def drop_db() -> None:
"""Empty database and delete uploaded files for dev environments."""
db.engine.execute("DROP TABLE IF EXISTS alembic_version;")
db.drop_all()
db.session.commit()
print('Database dropped.')
shutil.rmtree(app.config['UPLOAD_FOLDER'], ignore_errors=True)
print('Uploaded files deleted.')
@app.cli.command('set-admin')
@click.argument('username')
def set_admin(username: str) -> None:
"""Set admin rights for given user"""
try:
set_admin_rights(username)
print(f"User '{username}' updated.")
except UserNotFoundException:
print(f"User '{username}' not found.")
def main() -> None: def main() -> None:
options = {'bind': f'{HOST}:{PORT}', 'workers': WORKERS} options = {'bind': f'{HOST}:{PORT}', 'workers': WORKERS}
StandaloneApplication(app, options).run() StandaloneApplication(app, options).run()

View File

@ -6,7 +6,7 @@ from email.mime.text import MIMEText
from typing import Dict, Optional, Type, Union from typing import Dict, Optional, Type, Union
from flask import Flask from flask import Flask
from jinja2 import Environment, FileSystemLoader from jinja2 import Environment, FileSystemLoader, select_autoescape
from .utils_email import parse_email_url from .utils_email import parse_email_url
@ -38,7 +38,10 @@ class EmailMessage:
class EmailTemplate: class EmailTemplate:
def __init__(self, template_directory: str) -> None: def __init__(self, template_directory: str) -> None:
self._env = Environment(loader=FileSystemLoader(template_directory)) self._env = Environment(
autoescape=select_autoescape(['html', 'htm', 'xml']),
loader=FileSystemLoader(template_directory),
)
def get_content( def get_content(
self, template_name: str, lang: str, part: str, data: Dict self, template_name: str, lang: str, part: str, data: Dict

View File

@ -2,6 +2,7 @@ import os
import shutil import shutil
from typing import Any, Dict, Tuple, Union from typing import Any, Dict, Tuple, Union
import click
from flask import Blueprint, request, send_file from flask import Blueprint, request, send_file
from sqlalchemy import exc from sqlalchemy import exc
@ -18,13 +19,26 @@ from fittrackee.workouts.models import Record, Workout, WorkoutSegment
from fittrackee.workouts.utils_files import get_absolute_file_path from fittrackee.workouts.utils_files import get_absolute_file_path
from .decorators import authenticate, authenticate_as_admin from .decorators import authenticate, authenticate_as_admin
from .exceptions import UserNotFoundException
from .models import User, UserSportPreference from .models import User, UserSportPreference
from .utils import set_admin_rights
users_blueprint = Blueprint('users', __name__) users_blueprint = Blueprint('users', __name__)
USER_PER_PAGE = 10 USER_PER_PAGE = 10
@users_blueprint.cli.command('set-admin')
@click.argument('username')
def set_admin(username: str) -> None:
"""Set admin rights for given user"""
try:
set_admin_rights(username)
print(f"User '{username}' updated.")
except UserNotFoundException:
print(f"User '{username}' not found.")
@users_blueprint.route('/users', methods=['GET']) @users_blueprint.route('/users', methods=['GET'])
@authenticate @authenticate
def get_users(auth_user: User) -> Dict: def get_users(auth_user: User) -> Dict:

View File

@ -62,9 +62,9 @@ Sphinx = "^4.4.0"
[tool.poetry.scripts] [tool.poetry.scripts]
fittrackee = 'fittrackee.__main__:main' fittrackee = 'fittrackee.__main__:main'
fittrackee_set_admin = 'fittrackee.__main__:set_admin' fittrackee_set_admin = 'fittrackee.users.users:set_admin'
fittrackee_upgrade_db = 'fittrackee.__main__:upgrade_db' fittrackee_upgrade_db = 'fittrackee.__main__:upgrade_db'
fittrackee_worker = 'fittrackee.__main__:dramatiq_worker' fittrackee_worker = 'flask_dramatiq:worker'
[tool.black] [tool.black]
line-length = 79 line-length = 79