Skip to content

Commit

Permalink
Project refactor for beta release
Browse files Browse the repository at this point in the history
Signed-off-by: William José Moreno Reyes <[email protected]>

WIP

WIP

WIP

WIP

WIP

WIP

WIP

Signed-off-by: William José Moreno Reyes <[email protected]>

WIP

Signed-off-by: William José Moreno Reyes <[email protected]>

WIP

Signed-off-by: William José Moreno Reyes <[email protected]>

WIP

Signed-off-by: William José Moreno Reyes <[email protected]>

WIP

WIP

WIP

WIP

Signed-off-by: William José Moreno Reyes <[email protected]>
  • Loading branch information
williamjmorenor committed Feb 6, 2024
1 parent 90df0ec commit b14f422
Show file tree
Hide file tree
Showing 47 changed files with 1,640 additions and 1,165 deletions.
3 changes: 0 additions & 3 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,5 @@ jobs:
- name: Test with SQLite
run: |
CI=True pytest -v --exitfirst --cov=now_lms
- name: Test with SQLite and Redis Cache
run: |
CI=True DATABASE_URL=sqlite:// CACHE_REDIS_HOST=localhost CACHE_REDIS_PORT=6379 pytest -v --exitfirst --cov=now_lms
- name: Codecov
uses: codecov/codecov-action@v1
7 changes: 2 additions & 5 deletions .github/workflows/refactor.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions

name: Python package
name: Refactor

on:
push:
Expand All @@ -16,7 +16,7 @@ jobs:
# 3.8 Shared hosting
# 3.9 Ubi minimal
# 3.12 Last release
python-version: [3.8, 3.9, 3.12]
python-version: [3.8]

steps:
- uses: actions/checkout@v3
Expand All @@ -37,8 +37,5 @@ jobs:
- name: Test with SQLite
run: |
CI=True pytest -v --exitfirst --cov=now_lms
- name: Test with SQLite and Redis Cache
run: |
CI=True DATABASE_URL=sqlite:// CACHE_REDIS_HOST=localhost CACHE_REDIS_PORT=6379 pytest -v --exitfirst --cov=now_lms
- name: Codecov
uses: codecov/codecov-action@v1
123 changes: 74 additions & 49 deletions now_lms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,32 +36,29 @@
# Libreria estandar
# ---------------------------------------------------------------------------------------
import sys
from datetime import datetime
from os import cpu_count, environ
from platform import python_version
from turtle import update

# ---------------------------------------------------------------------------------------
# Librerias de terceros
# ---------------------------------------------------------------------------------------
import click
from flask import Flask, abort, flash, redirect, render_template, request, url_for
from flask import Flask, flash, render_template
from flask.cli import FlaskGroup
from flask_alembic import Alembic
from flask_login import LoginManager, current_user, login_required
from flask_login import LoginManager, current_user
from flask_mail import Mail
from flask_mde import Mde
from flask_uploads import UploadNotAllowed, configure_uploads
from flask_uploads import configure_uploads
from pg8000.dbapi import ProgrammingError as PGProgrammingError
from pg8000.exceptions import DatabaseError
from sqlalchemy.exc import ArgumentError, OperationalError, ProgrammingError
from sqlalchemy.exc import OperationalError, ProgrammingError
from werkzeug.exceptions import HTTPException

# ---------------------------------------------------------------------------------------
# Recursos locales
# ---------------------------------------------------------------------------------------
from now_lms.auth import perfil_requerido
from now_lms.bi import cambia_tipo_de_usuario_por_id
from now_lms.cache import cache, no_guardar_en_cache_global
from now_lms.cache import cache
from now_lms.config import (
CONFIGURACION,
DESARROLLO,
Expand All @@ -72,18 +69,7 @@
images,
log_messages,
)
from now_lms.db import (
MAXIMO_RESULTADOS_EN_CONSULTA_PAGINADA,
Configuracion,
Curso,
CursoRecurso,
DocenteCurso,
Usuario,
UsuarioGrupo,
UsuarioGrupoMiembro,
UsuarioGrupoTutor,
database,
)
from now_lms.db import Configuracion, Usuario, database
from now_lms.db.info import app_info
from now_lms.db.initial_data import (
asignar_cursos_a_categoria,
Expand All @@ -103,44 +89,39 @@
from now_lms.db.tools import (
crear_configuracion_predeterminada,
cuenta_cursos_por_programa,
elimina_imagen_usuario,
elimina_logo_perzonalizado,
elimina_logo_perzonalizado_curso,
elimina_logo_perzonalizado_programa,
logo_perzonalizado,
obtener_estilo_actual,
verifica_docente_asignado_a_curso,
verifica_estudiante_asignado_a_curso,
verifica_moderador_asignado_a_curso,
verificar_avance_recurso,
)
from now_lms.forms import ConfigForm, GrupoForm, MailForm, ThemeForm, UserForm
from now_lms.logs import log
from now_lms.misc import (
ESTILO,
ESTILO_ALERTAS,
GENEROS,
ICONOS_RECURSOS,
INICIO_SESION,
concatenar_parametros_a_url,
markdown_to_clean_hmtl,
)
from now_lms.modules.categories import category
from now_lms.modules.certificates import certificate
from now_lms.modules.courses import course
from now_lms.modules.messages import msg
from now_lms.modules.profiles.admin import admin_profile
from now_lms.modules.profiles.instructor import instructor_profile
from now_lms.modules.profiles.moderator import moderator_profile
from now_lms.modules.profiles.user import user_profile
from now_lms.modules.programs import program
from now_lms.modules.resources import resource_d
from now_lms.modules.settings import setting
from now_lms.modules.tags import tag
from now_lms.modules.users import user
from now_lms.modules.home import home
from now_lms.version import VERSION
from now_lms.modules.groups import group
from now_lms.vistas.categories import category
from now_lms.vistas.certificates import certificate
from now_lms.vistas.courses import course
from now_lms.vistas.groups import group
from now_lms.vistas.home import home
from now_lms.vistas.messages import msg
from now_lms.vistas.profiles.admin import admin_profile
from now_lms.vistas.profiles.instructor import instructor_profile
from now_lms.vistas.profiles.moderator import moderator_profile
from now_lms.vistas.profiles.user import user_profile
from now_lms.vistas.programs import program
from now_lms.vistas.resources import resource_d
from now_lms.vistas.settings import setting
from now_lms.vistas.tags import tag
from now_lms.vistas.users import user
from now_lms.vistas.web_error_codes import web_error

# ---------------------------------------------------------------------------------------
# Metadatos
Expand Down Expand Up @@ -225,6 +206,7 @@ def registrar_modulos_en_la_aplicacion_principal(flask_app: Flask):
flask_app.register_blueprint(instructor_profile)
flask_app.register_blueprint(moderator_profile)
flask_app.register_blueprint(user_profile)
flask_app.register_blueprint(web_error)


# ---------------------------------------------------------------------------------------
Expand Down Expand Up @@ -277,6 +259,30 @@ def no_autorizado(): # pragma: no cover
# ---------------------------------------------------------------------------------------
# Páginas de error personalizadas.
# ---------------------------------------------------------------------------------------


# Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/402
class PaymentRequired(HTTPException):
"""402 Payment Required"""

code = 402
description = """
The HTTP 402 Payment Required is a nonstandard response status code that is reserved
for future use. This status code was created to enable digital cash or (micro) payment
systems and would indicate that the requested content is not available until the client
makes a payment.
"""


# Errores standares
def handle_402(error):
if error:
return render_template("error_pages/403.html")


lms_app.register_error_handler(PaymentRequired, handle_402)


@lms_app.errorhandler(403)
@cache.cached()
def error_403(error): # pragma: no cover
Expand All @@ -293,6 +299,14 @@ def error_404(error): # pragma: no cover
return render_template("error_pages/404.html"), 404


@lms_app.errorhandler(405)
@cache.cached()
def error_405(error): # pragma: no cover
"""Pagina personalizada para metodos no permitidos."""
assert error is not None # nosec B101
return render_template("error_pages/405.html"), 405


@lms_app.errorhandler(500)
@cache.cached()
def error_500(error): # pragma: no cover
Expand Down Expand Up @@ -349,7 +363,7 @@ def carga_configuracion_del_sitio_web_desde_db(): # pragma: no cover
# ---------------------------------------------------------------------------------------
# Funciones auxiliares para la administracion y configuración inicial de la aplicacion
# ---------------------------------------------------------------------------------------
def initial_setup(with_examples=False):
def initial_setup(with_examples=False, with_test_data=False):
"""Inicializa una nueva bases de datos"""
with lms_app.app_context():
log.info("Creando esquema de base de datos.")
Expand All @@ -358,9 +372,9 @@ def initial_setup(with_examples=False):
log.debug("Esquema de base de datos creado correctamente.")
log.info("Cargando datos de muestra.")
crear_configuracion_predeterminada()
crear_usuarios_predeterminados(with_examples)
crear_curso_predeterminado()
if DESARROLLO or environ.get("CI") or with_examples:
crear_usuarios_predeterminados()
if with_examples:
crear_categorias()
crear_etiquetas()
log.debug("Cargando datos de prueba.")
Expand All @@ -373,6 +387,11 @@ def initial_setup(with_examples=False):
crear_programa()
crear_recurso_descargable()
log.debug("Datos de muestra cargados correctamente.")
if DESARROLLO or environ.get("CI") or with_test_data:
from now_lms.db.data_test import crear_data_para_pruebas

crear_data_para_pruebas()

log.info("NOW - LMS iniciado correctamente.")


Expand Down Expand Up @@ -418,7 +437,7 @@ def init_app(with_examples=False): # pragma: no cover

if DB_ACCESS and not DB_INICIALIZADA:
log.info("Iniciando nueva base de datos.")
initial_setup(with_examples=False)
initial_setup(with_examples=with_examples)
else:
log.trace("Acceso a base de datos verificado.")
config = Configuracion.query.first()
Expand Down Expand Up @@ -457,10 +476,15 @@ def command(as_module=False) -> None: # pragma: no cover

@lms_app.cli.command()
@click.option("--with-examples", is_flag=True, default=False, help="Load example data at setup.")
def setup(with_examples): # pragma: no cover
@click.option("--with-tests", is_flag=True, default=False, help="Load data for testing.")
def setup(with_examples=False, with_tests=False): # pragma: no cover
"""Inicia al aplicacion."""
lms_app.app_context().push()
initial_setup(with_examples)
if with_tests:
from now_lms.db.data_test import crear_data_para_pruebas

crear_data_para_pruebas()


@lms_app.cli.command()
Expand All @@ -477,12 +501,13 @@ def upgrade_db(): # pragma: no cover

@lms_app.cli.command()
@click.option("--with-examples", is_flag=True, default=False, help="Load example data at setup.")
def resetdb(with_examples) -> None: # pragma: no cover
@click.option("--with-tests", is_flag=True, default=False, help="Load data for testing.")
def resetdb(with_examples=False, with_tests=False) -> None: # pragma: no cover
"""Elimina la base de datos actual e inicia una nueva."""
lms_app.app_context().push()
cache.clear()
database.drop_all()
initial_setup(with_examples)
initial_setup(with_examples, with_tests)


@lms_app.cli.command()
Expand Down
1 change: 1 addition & 0 deletions now_lms/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,7 @@ class Certificado(database.Model, BaseTabla):
"""Plantilla para generar un certificado."""

titulo = database.Column(database.String(50))
descripcion = database.Column(database.String(500))
habilitado = database.Column(database.Boolean())


Expand Down
Loading

0 comments on commit b14f422

Please sign in to comment.