Skip to content

Commit

Permalink
Merge pull request #31 from guivaloz/guivaloz/externos-con-clave
Browse files Browse the repository at this point in the history
Validation Exception Handler
  • Loading branch information
guivaloz authored Jul 18, 2024
2 parents 54af3c2 + b1fcf02 commit 0b97598
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 41 deletions.
48 changes: 26 additions & 22 deletions carina/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,33 @@
"""

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi_pagination import add_pagination

from carina.v4.autoridades.paths import autoridades
from carina.v4.bitacoras.paths import bitacoras
from carina.v4.distritos.paths import distritos
from carina.v4.domicilios.paths import domicilios
from carina.v4.entradas_salidas.paths import entradas_salidas
from carina.v4.estados.paths import estados
from carina.v4.exh_areas.paths import exh_areas
from carina.v4.exh_exhortos.paths import exh_exhortos
from carina.v4.exh_exhortos_archivos.paths import exh_exhortos_archivos
from carina.v4.exh_exhortos_partes.paths import exh_exhortos_partes
from carina.v4.exh_exhortos_videos.paths import exh_exhortos_videos
from carina.v4.exh_externos.paths import exh_externos
from carina.v4.materias.paths import materias
from carina.v4.modulos.paths import modulos
from carina.v4.municipios.paths import municipios
from carina.v4.oficinas.paths import oficinas
from carina.v4.permisos.paths import permisos
from carina.v4.roles.paths import roles
from carina.v4.tareas.paths import tareas
from carina.v4.usuarios.paths import usuarios
from carina.v4.usuarios_roles.paths import usuarios_roles
from config.settings import get_settings

from .v4.autoridades.paths import autoridades
from .v4.bitacoras.paths import bitacoras
from .v4.distritos.paths import distritos
from .v4.domicilios.paths import domicilios
from .v4.entradas_salidas.paths import entradas_salidas
from .v4.estados.paths import estados
from .v4.exh_areas.paths import exh_areas
from .v4.exh_exhortos.paths import exh_exhortos
from .v4.exh_exhortos_archivos.paths import exh_exhortos_archivos
from .v4.exh_exhortos_partes.paths import exh_exhortos_partes
from .v4.exh_exhortos_videos.paths import exh_exhortos_videos
from .v4.exh_externos.paths import exh_externos
from .v4.materias.paths import materias
from .v4.modulos.paths import modulos
from .v4.municipios.paths import municipios
from .v4.oficinas.paths import oficinas
from .v4.permisos.paths import permisos
from .v4.roles.paths import roles
from .v4.tareas.paths import tareas
from .v4.usuarios.paths import usuarios
from .v4.usuarios_roles.paths import usuarios_roles
from lib.fastapi_validation_exception_handler import validation_exception_handler


def create_app() -> FastAPI:
Expand All @@ -52,6 +53,9 @@ def create_app() -> FastAPI:
allow_headers=["*"],
)

# Override the default validation exception handler
app.add_exception_handler(RequestValidationError, handler=validation_exception_handler)

# Rutas
app.include_router(autoridades, include_in_schema=False)
app.include_router(bitacoras, include_in_schema=False)
Expand Down
10 changes: 5 additions & 5 deletions carina/v4/exh_externos/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,23 @@

from ...core.permisos.models import Permiso
from ..usuarios.authentications import UsuarioInDB, get_current_active_user
from .crud import get_exh_externo
from .crud import get_exh_externo_with_clave
from .schemas import OneExhExternoOut

exh_externos = APIRouter(prefix="/v4/exh_externos", tags=["externos"])


@exh_externos.get("/{exh_externo_id}", response_model=OneExhExternoOut)
async def detalle_exh_exhorto_video(
@exh_externos.get("/{exh_externo_clave}", response_model=OneExhExternoOut)
async def detalle_exh_externo(
current_user: Annotated[UsuarioInDB, Depends(get_current_active_user)],
database: Annotated[Session, Depends(get_db)],
exh_exhorto_video_id: int,
exh_externo_clave: str,
):
"""Detalle de un video a partir de su id"""
if current_user.permissions.get("EXH EXHORTOS VIDEOS", 0) < Permiso.VER:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
try:
exh_externo = get_exh_externo(database, exh_exhorto_video_id)
exh_externo = get_exh_externo_with_clave(database, exh_externo_clave)
except MyAnyError as error:
return OneExhExternoOut(success=False, errors=[str(error)])
return OneExhExternoOut(success=True, data=exh_externo)
22 changes: 22 additions & 0 deletions lib/fastapi_validation_exception_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
FastAPI Validation Exception Handler
"""

from fastapi import Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse


def validation_exception_handler(request: Request, exc: RequestValidationError):
"""Manejador de excepciones de validación"""
payload = {
"success": False,
"message": "Error de validación",
"errors": list(exc.errors()),
"data": [],
}
return JSONResponse(
content=jsonable_encoder(payload),
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ black = "^24.4"
faker = "^26.0"
isort = "^5.13"
poetry-plugin-export = "^1.8"
pre-commit = "^3.6"
pylint = "^3.0"
pylint-sqlalchemy = "^0.3"
pytest = "^8.2"
pre-commit = "^3.6"

[build-system]
requires = ["poetry-core"]
Expand Down
35 changes: 22 additions & 13 deletions tests/test_exh_exhortos.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,36 +100,45 @@ def test_post_exh_exhorto(self):
"observaciones": "CELEBRIDADES QUE SE VAN A DIVORCIAR",
"archivos": archivos,
}
response = requests.post(
exhorto_response = requests.post(
url=f"{config['api_base_url']}/exh_exhortos",
headers={"X-Api-Key": config["api_key"]},
timeout=config["timeout"],
json=datos_nuevo_exhorto,
)
self.assertEqual(response.status_code, 200)
data = response.json()
if "success" in data and data["success"] is False and "errors" in data:
print("ERRORES: ", data["errors"])
self.assertEqual(data["success"], True)
# self.assertEqual(data["data"]["exhortoOrigenId"], exhorto_origen_id)
exhorto_res_json = exhorto_response.json()
if "success" in exhorto_res_json:
if exhorto_res_json["success"] is False:
if "message" in exhorto_res_json:
print("MENSAJE: ", exhorto_res_json["message"])
if "errors" in exhorto_res_json:
print("ERRORES: ", exhorto_res_json["errors"])
self.assertEqual(exhorto_res_json["success"], True)
else:
self.assertEqual(exhorto_response.status_code, 200)

# Mandar un archivo multipart/form-data
for archivo in archivos:
time.sleep(2) # Pausa de 2 segundos
archivo_prueba_nombre = archivo["nombreArchivo"]
with open(f"tests/{archivo_prueba_nombre}", "rb") as archivo_prueba:
response = requests.post(
archivo_response = requests.post(
url=f"{config['api_base_url']}/exh_exhortos_archivos/upload",
headers={"X-Api-Key": config["api_key"]},
timeout=config["timeout"],
params={"exhortoOrigenId": exhorto_origen_id},
files={"archivo": (archivo_prueba_nombre, archivo_prueba, "application/pdf")},
)
self.assertEqual(response.status_code, 200)
data = response.json()
# self.assertEqual(data["success"], True)
if data["success"] is False:
print("ERRORES: ", data["errors"])
archivo_res_json = archivo_response.json()
if "success" in archivo_res_json:
if archivo_res_json["success"] is False:
if "message" in archivo_res_json:
print("MENSAJE: ", archivo_res_json["message"])
if "errors" in archivo_res_json:
print("ERRORES: ", archivo_res_json["errors"])
self.assertEqual(archivo_res_json["success"], True)
else:
self.assertEqual(archivo_response.status_code, 200)


if __name__ == "__main__":
Expand Down

0 comments on commit 0b97598

Please sign in to comment.