Пример #1
0
    def desde_str(tipo_carpeta: str) -> 'TipoCarpeta':
        try:
            return TipoCarpeta[tipo_carpeta.upper()]

        except Exception as e:
            mensaje = f'Error al convertir el tipo de carpeta {tipo_carpeta} -> {e}, se usara el predefinido TEXTO'
            get_logger().error(mensaje)

            return TipoCarpeta.TEXTO
def _descargar_csv(url_completa: str) -> bytes:
    '''
    Descargar el csv de la pagina de taiga mediante un GET pasandole la URL
    '''
    get_logger().info(f'Descargando CSV con url -> {url_completa}')

    respuesta = requests.get(url_completa)

    if not respuesta.ok:
        mensaje = f'El servicio de Taiga no respondio un 200 -> http: {respuesta.status_code}, {respuesta.text}'
        raise AppException(Errores.ERROR_API_TAIGA, mensaje)

    return respuesta.content
def iniciar_proceso_automatico():
    '''
    Obtine el json guardado con la configuracion autormatica de los reportes
    '''
    configs = obtener_json_config()
    get_logger().info(
        f'Iniciando proceso automatico con la siguiente config: {configs}')

    for config in obtener_json_config():
        job = scheduler_util.agregar_job(_sched, _funcion, config.cron,
                                         config.nombre)
        job.args = [config]
        job.func = generar_reporte

    scheduler_util.inciar_scheduler(_sched)
def _guardar_reporte_en_git(config: ReportesConfig, contenido_reporte: bytes):
    '''
    Guarda el reporte en git clonando el proyecto, creando el archivo de reporte,
    commiteando y pusheando
    '''
    repo = git_util.clonar_repo_git(config.git)
    get_logger().info(
        f'Repo clonado en la ruta: {repo.working_dir} con la url: {config.git.url_repo}'
    )

    nombre_reporte = _nombre_reporte_final(config)
    ruta_reporte = os.path.join(repo.working_dir, nombre_reporte)

    with open(ruta_reporte, 'wb') as reporte_archivo:
        reporte_archivo.write(contenido_reporte)

    mensaje_commit = f'Se sube reporte de forma automatica con nombre: {nombre_reporte}'
    git_util.pushear_a_master(repo, mensaje_commit)

    git_util._borrar_carpeta_si_existe(repo.working_dir)
def obtener_json_config() -> List[ReportesConfig]:
    '''
    Obtine el json guardado con la configuracion automatica de los reportes
    '''
    try:
        ruta_completa = _DIRECTORIO_ARCHIVO_CONFIG + _NOMBRE_ARCHIVO_CONFIG

        if not os.path.exists(ruta_completa):
            mensaje = f'No se encontro el archivo de configuracion en \"{ruta_completa}\"'
            get_logger().info(mensaje)
            return []

        with open(ruta_completa, 'r') as archivo:
            json_config = json.load(archivo)

        return [ReportesConfig.from_dict(config) for config in json_config]

    except Exception as e:
        get_logger().exception(e)
        return []
def generar_reporte(config: ReportesConfig):
    '''
    Genera el reporte pdf y envia el email al finalizar
    '''
    reporte_json = generar_reporte_json(config)

    url_completa = _GENERADOR_PDF_HOST + config.url_generar_reporte
    get_logger().info(f'Ejecutando REST con url -> {url_completa}')

    try:
        headers = {'content-type': 'application/json'}
        resultado = requests.post(url_completa,
                                  data=json.dumps(reporte_json),
                                  headers=headers)
    except Exception as e:
        mensaje = 'Error desconocido en el servicio de para generar el reporte'
        get_logger().error(mensaje, exc_info=True)
        get_logger().exception(e)
        raise AppException(Errores.SERVICIO_GENERAR_REPORTE, mensaje)

    if resultado.status_code != 200:
        mensaje = f'Error servicio generar reporte -> URL: {url_completa}, STATUS: {resultado.status_code}, BODY: {resultado.text}'
        raise AppException(Errores.SERVICIO_GENERAR_REPORTE, mensaje)

    contenido_reporte = resultado.content

    _enviar_email(config, contenido_reporte)
    _guardar_reporte_en_git(config, contenido_reporte)
Пример #7
0
from http import HTTPStatus

from flask import Blueprint, jsonify, request
from werkzeug.exceptions import HTTPException

from apps.configs.loggers import get_logger
from apps.models.errores import AppException

__version__ = '1.0.1'

error_handler_bp = Blueprint('handlers', __name__)

logger = get_logger()


@error_handler_bp.app_errorhandler(HTTPException)
def handle_exception(httpe):
    return '', httpe.code


@error_handler_bp.app_errorhandler(Exception)
def handle_exception(e):
    logger.exception(e)
    return '', HTTPStatus.INTERNAL_SERVER_ERROR


@error_handler_bp.app_errorhandler(AppException)
def handle_business_exception(ae: AppException):
    logger.warning(ae.to_dict())
    return ae.respuesta_json()
def handle_business_exception(ae: AppException):
    get_logger().warning(ae.to_dict())
    return ae.respuesta_json()
def handle_exception(e):
    get_logger().exception(e)
    return '', HTTPStatus.INTERNAL_SERVER_ERROR
Пример #10
0
import json
import os

from flask import Flask, jsonify

import apps.configs.lector_variables as var
from apps.configs.loggers import get_logger
import apps.services.taiga.taiga_scheduler_service as taiga_scheduler_service
from apps.configs.error_handlers import error_handler_bp
from apps.configs.variables import Var
from apps.services.taiga.taiga_reportes_config_service import \
    guardar_json_config
from apps.utils.carga_dinamica_blue_prints import registrar_blue_prints

_PYTHON_HOST = var.get(Var.PYTHON_HOST)
_PYTHON_PORT = int(var.get(Var.PYTHON_PORT))
_CRON_REPORTES_AUTOMATICOS_ACTIVADO = bool(
    var.get(Var.CRON_REPORTES_AUTOMATICOS_ACTIVADO))

app = Flask(__name__)
app.register_blueprint(error_handler_bp)

registrar_blue_prints(app, 'apps/routes')

if _CRON_REPORTES_AUTOMATICOS_ACTIVADO:
    get_logger().info('Scheduler de reportes automaticos ACTIVADO')
    taiga_scheduler_service.iniciar_proceso_automatico()

if __name__ == "__main__":
    app.run(host=_PYTHON_HOST, port=_PYTHON_PORT, debug=True)