Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit eb92a3b

Browse files
committed
Backend: Día 3
1 parent 7a75488 commit eb92a3b

File tree

9 files changed

+79
-8
lines changed

9 files changed

+79
-8
lines changed
108 Bytes
Binary file not shown.
Binary file not shown.
824 Bytes
Binary file not shown.

Backend/FastAPI/main.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,15 @@
77
# Instala FastAPI: pip install "fastapi[all]"
88

99
from fastapi import FastAPI
10+
from routers import products, users
1011

1112
app = FastAPI()
1213

14+
# Routers - Clase en vídeo (08/12/2022): https://www.twitch.tv/videos/1673759045
15+
app.include_router(products.router)
16+
app.include_router(users.router)
17+
18+
1319
# Url local: http://127.0.0.1:8000
1420

1521

Binary file not shown.
Binary file not shown.

Backend/FastAPI/routers/products.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Clase en vídeo (08/12/2022): https://www.twitch.tv/videos/1673759045
2+
3+
### Products API ###
4+
5+
from fastapi import APIRouter
6+
7+
router = APIRouter(prefix="/products",
8+
tags=["products"],
9+
responses={404: {"message": "No encontrado"}})
10+
11+
products_list = ["Producto 1", "Producto 2",
12+
"Producto 3", "Producto 4", "Producto 5"]
13+
14+
15+
@router.get("/")
16+
async def products():
17+
return products_list
18+
19+
20+
@router.get("/{id}")
21+
async def products(id: int):
22+
return products_list[id]

Backend/FastAPI/users.py renamed to Backend/FastAPI/routers/users.py

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22

33
### Users API ###
44

5-
from fastapi import FastAPI
5+
from fastapi import APIRouter, HTTPException
66
from pydantic import BaseModel
77

88
# Inicia el server: uvicorn users:app --reload
99

10-
app = FastAPI()
10+
router = APIRouter()
1111

1212

1313
class User(BaseModel):
@@ -24,29 +24,71 @@ class User(BaseModel):
2424
User(id=3, name="Brais", surname="Dahlberg", url="https://haakon.com", age=33)]
2525

2626

27-
@app.get("/usersjson")
27+
@router.get("/usersjson")
2828
async def usersjson(): # Creamos un JSON a mano
2929
return [{"name": "Brais", "surname": "Moure", "url": "https://moure.dev", "age": 35},
3030
{"name": "Moure", "surname": "Dev",
3131
"url": "https://mouredev.com", "age": 35},
3232
{"name": "Haakon", "surname": "Dahlberg", "url": "https://haakon.com", "age": 33}]
3333

3434

35-
@app.get("/users")
35+
@router.get("/users")
3636
async def users():
3737
return users_list
3838

3939

40-
@app.get("/user/{id}") # Path
40+
@router.get("/user/{id}") # Path
4141
async def user(id: int):
4242
return search_user(id)
4343

4444

45-
@app.get("/user/") # Query
45+
@router.get("/user/") # Query
4646
async def user(id: int):
4747
return search_user(id)
4848

4949

50+
# Clase en vídeo (08/12/2022): https://www.twitch.tv/videos/1673759045
51+
52+
53+
@router.post("/user/", response_model=User, status_code=201)
54+
async def user(user: User):
55+
if type(search_user(user.id)) == User:
56+
raise HTTPException(status_code=404, detail="El usuario ya existe")
57+
58+
users_list.append(user)
59+
return user
60+
61+
62+
@router.put("/user/")
63+
async def user(user: User):
64+
65+
found = False
66+
67+
for index, saved_user in enumerate(users_list):
68+
if saved_user.id == user.id:
69+
users_list[index] = user
70+
found = True
71+
72+
if not found:
73+
return {"error": "No se ha actualizado el usuario"}
74+
75+
return user
76+
77+
78+
@router.delete("/user/{id}")
79+
async def user(id: int):
80+
81+
found = False
82+
83+
for index, saved_user in enumerate(users_list):
84+
if saved_user.id == id:
85+
del users_list[index]
86+
found = True
87+
88+
if not found:
89+
return {"error": "No se ha eliminado el usuario"}
90+
91+
5092
def search_user(id: int):
5193
users = filter(lambda user: user.id == id, users_list)
5294
try:

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
> * Base de datos
2121
> * Despliegue en servidor
2222
>
23-
> **🔴 SIGUIENTE CLASE: Jueves 8 de Diciembre a las 20:00 (hora España)**
23+
> **🔴 SIGUIENTE CLASE: Miércoles 14 de Diciembre a las 20:00 (hora España)**
2424
25-
> 🗓 En [Discord](https://discord.gg/mouredev) tienes creado un [evento](https://discord.gg/mouredev?event=1048225560637214790) para que consultes la hora de tu país y añadas un recordatorio.
25+
> 🗓 En [Discord](https://discord.gg/mouredev) tienes creado un [evento](https://discord.gg/mouredev?event=1051412181721305158) para que consultes la hora de tu país y añadas un recordatorio.
2626
>
2727
> Mientras, aprovecha para practicar unos [retos de programación](https://retosdeprogramacion.com/semanales2022) y así ir mejorando poco a poco.
2828
>
@@ -40,6 +40,7 @@ Curso en el que aprenderemos a utilizar Python para backend e implementaremos un
4040
4141
* [Clase 1 - 24/11/2022 - Hola Mundo en FastAPI](https://www.twitch.tv/videos/1661716599)
4242
* [Clase 2 - 01/12/2022 - Operaciones con GET y peticiones HTTP](https://www.twitch.tv/videos/1667582141)
43+
* [Clase 3 - 08/12/2022 - Operaciones con POST, PUT, DELETE, códigos HTTP y Routers](https://www.twitch.tv/videos/1673759045)
4344

4445
### Curso de fundamentos desde cero
4546

0 commit comments

Comments
 (0)