-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapi.py
More file actions
68 lines (49 loc) · 2.21 KB
/
Copy pathapi.py
File metadata and controls
68 lines (49 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, constr, validator
import database as db
import helpers
headers = {"content-type": "charset=utf-8"}
class ModeloCliente(BaseModel):
dni: constr(min_length=3, max_length=3)
nombre: constr(min_length=2, max_length=30)
apellido: constr(min_length=2, max_length=30)
class ModeloCrearCliente(ModeloCliente):
@validator("dni")
def validar_dni(cls, dni):
if not helpers.dni_valido(dni, db.Clientes.lista):
raise ValueError("Cliente ya existente o DNI incorrecto")
return dni
app = FastAPI(
title="API del Gestor de clientes",
description="Ofrece diferentes funciones para gestionar los clientes.")
@app.get("/clientes/", tags=["Clientes"])
async def clientes():
content = [cliente.to_dict() for cliente in db.Clientes.lista]
return JSONResponse(content=content, headers=headers)
@app.get("/clientes/buscar/{dni}/", tags=["Clientes"])
async def clientes_buscar(dni: str):
cliente = db.Clientes.buscar(dni=dni)
if not cliente:
raise HTTPException(status_code=404, detail="Cliente no encontrado")
return JSONResponse(content=cliente.to_dict(), headers=headers)
@app.post("/clientes/crear/", tags=["Clientes"])
async def clientes_crear(datos: ModeloCrearCliente):
cliente = db.Clientes.crear(datos.dni, datos.nombre, datos.apellido)
if cliente:
return JSONResponse(content=cliente.to_dict(), headers=headers)
raise HTTPException(status_code=404)
@ app.put("/clientes/actualizar/", tags=["Clientes"])
async def clientes_actualizar(datos: ModeloCliente):
if db.Clientes.buscar(datos.dni):
cliente = db.Clientes.modificar(datos.dni, datos.nombre, datos.apellido)
if cliente:
return JSONResponse(content=cliente.to_dict(), headers=headers)
raise HTTPException(status_code=404)
@app.delete("/clientes/borrar/{dni}/", tags=["Clientes"])
async def clientes_borrar(dni: str):
if db.Clientes.buscar(dni=dni):
cliente = db.Clientes.borrar(dni=dni)
return JSONResponse(content=cliente.to_dict(), headers=headers)
raise HTTPException(status_code=404)
print("Servidor de la API...")