Skip to content

Commit

Permalink
Remove bank mongo id
Browse files Browse the repository at this point in the history
  • Loading branch information
4l3j0Ok committed Mar 28, 2024
1 parent f759522 commit 35548e0
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 31 deletions.
10 changes: 0 additions & 10 deletions src/models/bank.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
from pydantic import BaseModel
from bson import ObjectId


class Bank(BaseModel):
label: str
bcra_id: str


class BankDB(Bank):
id: str | None

def __init__(self, **bank):
if "_id" in bank and isinstance(bank["_id"], ObjectId):
bank["id"] = str(bank["_id"])
super().__init__(**bank)


class AdminCredentials(BaseModel):
username: str
password: str
4 changes: 1 addition & 3 deletions src/models/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ class Detail(TypedDict):


class Success(BaseModel):
input: str | int | dict | None
detail: Detail


class Failed(BaseModel):
input: str | int | dict | None
detail: Detail


class Result(BaseModel):
success: list[Success] | list
failed: list[Failed] | list
failed: list[Failed] | list
28 changes: 13 additions & 15 deletions src/modules/bank.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,40 @@
from modules import soup, messages, config
from modules.logger import logger
from models.bank import BankDB
from models.bank import Bank
from db.client import client
from bson import ObjectId
import os


db = client.bcra_scraper.banks


def get_banks(bank_id: str = None, as_dict: bool = False):
logger.info(f"Validando ID {bank_id}.")
if bank_id:
if not ObjectId.is_valid(bank_id):
logger.warning(f"ID {bank_id} inválido.")
return False, messages.ERR_SCHEMA.format(err_args="id")
def get_banks(bcra_id: str = None, as_dict: bool = False):
logger.info("Buscando bancos en la DB.")
result = list(db.find({"_id":ObjectId(bank_id)} if bank_id else None))
result = list(db.find({"bcra_id": bcra_id} if bcra_id else None))
if not result:
return False, messages.ERR_BANK_NOT_FOUND
banks = [BankDB(**bank) for bank in result] if not as_dict \
else [BankDB(**bank).model_dump() for bank in result]
banks = [Bank(**bank) for bank in result] if not as_dict \
else [Bank(**bank).model_dump() for bank in result]
return True, banks if len(banks) != 1 else banks[0]


def update_banks():
logger.info("Actualizando la lista de bancos con SOUP...")
data = soup.get_banks_from_url(config.BCRA_URL)
delete_query = {"bcra_id": {"$in": [bank["bcra_id"] for bank in data]}}
db.delete_many(delete_query)
result = db.insert_many(data)
return True, [str(bank_id) for bank_id in result.inserted_ids]
try:
db.delete_many(delete_query)
db.insert_many(data)
except Exception as ex:
logger.exception(ex)
return False, messages.ERR_FAILED_TO_UPDATE
return True, messages.MSG_SUCCESS_SAVE


def add_bank(bank):
logger.info("Agregando un nuevo banco...")
result = db.insert_one(bank.dict())
return True, str(result.inserted_id)
return True, messages.MSG_SUCCESS_SAVE


def validate_admin(credentials):
Expand Down
3 changes: 2 additions & 1 deletion src/modules/messages.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
ERR_BANK_NOT_FOUND = "Banco no encontrado."
ERR_BANK_ALREADY_EXISTS = "El banco con id {id} ya existe."
ERR_BANK_NOT_CHANGED = "El banco ingresado posee los mismos datos."
ERR_FAILED_TO_UPDATE = "No se pudo actualizar la lista de bancos."
ERR_SCHEMA = "Los datos ingresados no tienen la estructura adecuada. Argumentos faltantes o incorrectos: {err_args}."
MSG_SUCCESS_GENERIC = "Éxito al realizar la operación."
MSG_SUCCESS_SAVE = "Exito al guardar los datos."
MSG_ERROR_UNAUTHORIZED = "No autorizado."
MSG_ERROR_UNAUTHORIZED = "No autorizado."
2 changes: 0 additions & 2 deletions src/routers/bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ async def update_banks_list(credentials: AdminCredentials) -> Success:
)
)
return Success(
input=None,
detail=Detail(
payload={"ids": result},
message=messages.MSG_SUCCESS_SAVE
Expand Down Expand Up @@ -79,7 +78,6 @@ def add_bank(bank: Bank, credentials: AdminCredentials) -> Success:
)
)
return Success(
input=None,
detail=Detail(
payload={"id": result},
message=messages.MSG_SUCCESS_SAVE
Expand Down

0 comments on commit 35548e0

Please sign in to comment.