Skip to content

Commit

Permalink
Merge pull request #14 from guivaloz:guivaloz/upload-archivo
Browse files Browse the repository at this point in the history
Guivaloz/upload-archivo
  • Loading branch information
guivaloz authored May 14, 2024
2 parents f60eb40 + 859140f commit a9448e3
Show file tree
Hide file tree
Showing 9 changed files with 349 additions and 54 deletions.
50 changes: 38 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,32 +55,53 @@ Cuando NO se encuentra un registro el **status code** es **200** pero el **succe

Cuando la ruta NO existe, simplemente ocurre un **status code** con error **404**.

## Configure Poetry
## Instalación

Por defecto, con **poetry** el entorno se guarda en un directorio en `~/.cache/pypoetry/virtualenvs`
Crear el entorno virtual

Modifique para que el entorno se guarde en el mismo directorio que el proyecto
```bash
python3.11 -m venv .venv
```

Ingresar al entorno virtual

```bash
poetry config --list
poetry config virtualenvs.in-project true
source venv/bin/activate
```

Actualizar el gestor de paquetes **pip**

```bash
pip install --upgrade pip
```

Verifique que este en True
Instalar el paquete **wheel** para compilar las dependencias

```bash
pip install wheel
```

Instalar **poetry** en el entorno virtual si no lo tiene desde el sistema operativo

```bash
pip install poetry
```

Verificar que la configuracion `virtualenvs.in-project` sea True

```bash
poetry config virtualenvs.in-project
```

## Instalacion
Si es falso, configurar **poetry** para que use el entorno virtual dentro del proyecto

Instale el entorno virtual con **Python 3.11** y los paquetes necesarios
```bash
poetry config virtualenvs.in-project true
```

Instalar los paquetes por medio de **poetry**

```bash
python3.11 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install wheel
poetry install
```

Expand All @@ -96,6 +117,9 @@ DB_NAME=pjecz_plataforma_web
DB_USER=adminpjeczplataformaweb
DB_PASS=XXXXXXXXXXXXXXXX

# Google Cloud Storage
CLOUD_STORAGE_DEPOSITO=pjecz-desarrollo

# Origins
ORIGINS=http://localhost:3000

Expand Down Expand Up @@ -124,11 +148,13 @@ then
echo "-- Variables de entorno"
export $(grep -v '^#' .env | xargs)
# source .env && export $(sed '/^#/d' .env | cut -d= -f1)
echo " CLOUD_STORAGE_DEPOSITO: ${CLOUD_STORAGE_DEPOSITO}"
echo " DB_HOST: ${DB_HOST}"
echo " DB_PORT: ${DB_PORT}"
echo " DB_NAME: ${DB_NAME}"
echo " DB_USER: ${DB_USER}"
echo " DB_PASS: ${DB_PASS}"
echo " GOOGLE_APPLICATION_CREDENTIALS: ${GOOGLE_APPLICATION_CREDENTIALS}"
echo " ORIGINS: ${ORIGINS}"
echo " SALT: ${SALT}"
echo
Expand Down
10 changes: 7 additions & 3 deletions carina/v4/exh_exhortos/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from sqlalchemy.orm import Session

from lib.exceptions import MyIsDeletedError, MyNotExistsError
from lib.exceptions import MyIsDeletedError, MyNotExistsError, MyNotValidParamError
from ...core.estados.models import Estado
from ...core.exh_exhortos.models import ExhExhorto
from ...core.exh_exhortos_archivos.models import ExhExhortoArchivo
Expand All @@ -26,9 +26,13 @@ def get_exh_exhortos(database: Session) -> Any:
return consulta.filter_by(estatus="A").order_by(ExhExhorto.id)


def get_exh_exhorto(database: Session, exh_exhorto_id: int) -> ExhExhorto:
def get_exh_exhorto(database: Session, exhorto_origen_id: str) -> ExhExhorto:
"""Consultar un exhorto por su id"""
exh_exhorto = database.query(ExhExhorto).get(exh_exhorto_id)
try:
uuid.UUID(exhorto_origen_id)
except ValueError as error:
raise MyNotValidParamError("No es un UUID válido") from error
exh_exhorto = database.query(ExhExhorto).filter_by(exhorto_origen_id=exhorto_origen_id).first()
if exh_exhorto is None:
raise MyNotExistsError("No existe ese exhorto")
if exh_exhorto.estatus != "A":
Expand Down
10 changes: 6 additions & 4 deletions carina/v4/exh_exhortos/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,19 @@ async def paginado_exh_exhortos(
return paginate(resultados)


@exh_exhortos.get("/{exh_exhorto_id}", response_model=OneExhExhortoOut)
@exh_exhortos.get("/{exhorto_origen_id}", response_model=OneExhExhortoOut)
async def detalle_exh_exhorto(
current_user: Annotated[UsuarioInDB, Depends(get_current_active_user)],
database: Annotated[Session, Depends(get_db)],
exh_exhorto_id: int,
exhorto_origen_id: str,
):
"""Detalle de una exhorto a partir de su id"""
if current_user.permissions.get("EXH EXHORTOS", 0) < Permiso.VER:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")

# Consultar el exhorto
try:
exh_exhorto = get_exh_exhorto(database, exh_exhorto_id)
exh_exhorto = get_exh_exhorto(database, exhorto_origen_id)
except MyAnyError as error:
return OneExhExhortoOut(success=False, errors=[str(error)])

Expand Down Expand Up @@ -86,7 +88,7 @@ async def detalle_exh_exhorto(
)
exh_exhorto.archivos = archivos

# Entregar un exhorto
# Entregar
return OneExhExhortoOut(success=True, data=exh_exhorto)


Expand Down
9 changes: 3 additions & 6 deletions carina/v4/exh_exhortos_archivos/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,11 @@
from ...core.exh_exhortos_archivos.models import ExhExhortoArchivo


def get_exh_exhortos_archivos(
database: Session,
exh_exhorto_id: int = None,
) -> Any:
def get_exh_exhortos_archivos(database: Session, exhorto_origen_id: str = None) -> Any:
"""Consultar los archivos activos"""
consulta = database.query(ExhExhortoArchivo)
if exh_exhorto_id is not None:
exh_exhorto = get_exh_exhorto(database, exh_exhorto_id)
if exhorto_origen_id is not None:
exh_exhorto = get_exh_exhorto(database, exhorto_origen_id)
consulta = consulta.filter_by(exh_exhorto_id=exh_exhorto.id)
return consulta.filter_by(estatus="A").order_by(ExhExhortoArchivo.id)

Expand Down
73 changes: 70 additions & 3 deletions carina/v4/exh_exhortos_archivos/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,30 @@
Exh Exhortos Archivos v4, rutas (paths)
"""

from datetime import datetime
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status, UploadFile
from fastapi_pagination.ext.sqlalchemy import paginate

from config.settings import get_settings
from lib.database import Session, get_db
from lib.exceptions import MyAnyError
from lib.fastapi_pagination_custom_page import CustomPage
from lib.google_cloud_storage import get_blob_name_from_url, get_media_type_from_filename, get_file_from_gcs, upload_file_to_gcs

from ...core.permisos.models import Permiso
from ..exh_exhortos.crud import get_exh_exhorto
from ..usuarios.authentications import UsuarioInDB, get_current_active_user
from .crud import get_exh_exhortos_archivos, get_exh_exhorto_archivo
from .schemas import ExhExhortoArchivoOut, OneExhExhortoArchivoOut, ExhExhortoArchivoFileIn
from .schemas import (
ExhExhortoArchivoFileDataAcuseOut,
ExhExhortoArchivoFileDataArchivoOut,
ExhExhortoArchivoFileDataOut,
ExhExhortoArchivoFileOut,
ExhExhortoArchivoOut,
OneExhExhortoArchivoOut,
)

exh_exhortos_archivos = APIRouter(prefix="/v4/exh_exhortos_archivos", tags=["exhortos"])

Expand Down Expand Up @@ -57,7 +68,63 @@ async def upload_exh_exhorto_archivo(
exhortoOrigenId: str,
archivo: UploadFile,
):
"""Entregar un archivo"""
"""Recibir un archivo"""
if current_user.permissions.get("EXH EXHORTOS ARCHIVOS", 0) < Permiso.CREAR:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
return {"message": archivo.filename}

# Consultar y validar el exhorto a partir del exhortoOrigenId
try:
exh_exhorto = get_exh_exhorto(database, exhortoOrigenId)
except MyAnyError as error:
return ExhExhortoArchivoFileOut(success=False, errors=[str(error)])

# Consultar los archivos del exhorto
exh_exhortos_archivos = get_exh_exhortos_archivos(database, exhortoOrigenId).all()

# Buscar el archivo del exhorto a partir del nombre del archivo
se_encontro = False
for exh_exhorto_archivo in exh_exhortos_archivos:
if exh_exhorto_archivo.nombre_archivo == archivo.filename:
se_encontro = True
break

# Si NO se encontró el archivo, entonces entregar un error
if not se_encontro:
return ExhExhortoArchivoFileOut(success=False, errors=["No se encontró el archivo"])

# Validar la integridad del archivo con los hashes

# Almacenar el archivo en Google Storage
settings = get_settings()
upload_file_to_gcs(
bucket_name=settings.cloud_storage_deposito,
blob_name=f"exh_exhortos_archivos/YYYY/MM/DD/{archivo.filename}",
content_type="application/pdf",
data=archivo.file,
)

# Definir los datos del archivo para la respuesta
archivo = ExhExhortoArchivoFileDataArchivoOut(
nombreArchivo=archivo.filename,
tamano=1024,
)

# Definir los datos del acuse para la respuesta
acuse = ExhExhortoArchivoFileDataAcuseOut(
exhortoOrigenId="",
folioSeguimiento="",
fechaHoraRecepcion=datetime.now(),
municipioAreaRecibeId=1,
areaRecibeId="",
areaRecibeNombre="",
urlInfo="",
)

# Juntar los datos para la respuesta
data = ExhExhortoArchivoFileDataOut(
archivo=archivo,
acuse=acuse,
)

# Entregar la respuesta
return ExhExhortoArchivoFileOut(success=True, data=data)
4 changes: 4 additions & 0 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Para desarrollo debe crear un archivo .env en la raíz del proyecto
con las siguientes variables:
- CLOUD_STORAGE_DEPOSITO
- DB_HOST
- DB_PORT
- DB_NAME
Expand All @@ -21,6 +22,7 @@
https://console.cloud.google.com/security/secret-manager
y cree como secretos las siguientes variable de entorno
- pjecz_carina_api_key_cloud_storage_deposito
- pjecz_carina_api_key_db_host
- pjecz_carina_api_key_db_port
- pjecz_carina_api_key_db_name
Expand All @@ -34,6 +36,7 @@
- PROJECT_ID: justicia-digital-gob-mx
- SERVICE_PREFIX: pjecz_carina_api_key
"""

import os
from functools import lru_cache

Expand Down Expand Up @@ -68,6 +71,7 @@ def get_secret(secret_id: str) -> str:
class Settings(BaseSettings):
"""Settings"""

cloud_storage_deposito: str = get_secret("cloud_storage_deposito")
db_host: str = get_secret("db_host")
db_port: int = get_secret("db_port")
db_name: str = get_secret("db_name")
Expand Down
Loading

0 comments on commit a9448e3

Please sign in to comment.