Spaces:
Sleeping
Sleeping
from library.librerias import * | |
from models.gastos import Gastos | |
router = APIRouter( | |
prefix="/gastos", | |
tags=["Gastos"], | |
responses={404: {"description": "No encontrado"}}, | |
) | |
"""CREATE TABLE gastos ( | |
ID_Gasto INTEGER PRIMARY KEY AUTOINCREMENT, | |
Tipo TEXT, | |
Monto REAL, | |
Fecha DATE | |
); | |
""" | |
def get_gastos(): | |
try: | |
with DatabaseConnection().get_connection() as conn: | |
cursor = conn.cursor() | |
cursor.execute("SELECT * FROM gastos") | |
gastos = cursor.fetchall() | |
return gastos | |
except Exception as e: | |
print(e) | |
return [] | |
# @router.post("/") | |
def post_gasto(gasto: Gastos): | |
try: | |
with DatabaseConnection().get_connection() as conn: | |
cursor = conn.cursor() | |
cursor.execute( | |
"INSERT INTO gastos (Tipo, Monto, Fecha) VALUES (?, ?, ?)", | |
(gasto.Tipo, gasto.Monto, gasto.Fecha), | |
) | |
conn.commit() | |
return {"message": "Gasto creado"} | |
except Exception as e: | |
print(e) | |
return [] | |
# @router.put("/") | |
def put_gasto(gasto: Gastos): | |
try: | |
with DatabaseConnection().get_connection() as conn: | |
cursor = conn.cursor() | |
cursor.execute( | |
"UPDATE gastos SET Tipo = ?, Monto = ?, Fecha = ? WHERE ID_Gasto = ?", | |
(gasto.Tipo, gasto.Monto, gasto.Fecha, gasto.ID_Gasto), | |
) | |
conn.commit() | |
return {"message": "Gasto actualizado"} | |
except Exception as e: | |
print(e) | |
return [] | |
# @router.delete("/{ID_Gasto}") | |
def delete_gasto(ID_Gasto: int): | |
try: | |
with DatabaseConnection().get_connection() as conn: | |
cursor = conn.cursor() | |
cursor.execute("DELETE FROM gastos WHERE ID_Gasto = ?", (ID_Gasto,)) | |
conn.commit() | |
return {"message": "Gasto eliminado"} | |
except Exception as e: | |
print(e) | |
return [] | |
# listar gastos de una fecha en especifico con formato YYYY-MM-DD | |
def get_gastos_by_date(Fecha: str): | |
try: | |
fecha = datetime.strptime(Fecha, "%Y-%m-%d").date() | |
with DatabaseConnection().get_connection() as conn: | |
cursor = conn.cursor() | |
cursor.execute("SELECT * FROM gastos WHERE Fecha = ?", (fecha,)) | |
gastos = cursor.fetchall() | |
return gastos | |
except Exception as e: | |
print(e) | |
return [] | |