forked from platzi/curso-fastapi-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
110 lines (95 loc) · 3.71 KB
/
main.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
from fastapi import Depends, FastAPI, Body, HTTPException, Path, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
from typing import Optional, List
from jwt_manager import create_token, validate_token
from fastapi.security import HTTPBearer
app = FastAPI()
app.title = "Mi aplicación con FastAPI"
app.version = "0.0.1"
class JWTBearer(HTTPBearer):
async def __call__(self, request: Request):
auth = await super().__call__(request)
data = validate_token(auth.credentials)
if data['email'] != "admin@gmail.com":
raise HTTPException(status_code=403, detail="Credenciales son invalidas")
class User(BaseModel):
email:str
password:str
class Movie(BaseModel):
id: Optional[int] = None
title: str = Field(min_length=5, max_length=15)
overview: str = Field(min_length=15, max_length=50)
year: int = Field(le=2022)
rating:float = Field(ge=1, le=10)
category:str = Field(min_length=5, max_length=15)
class Config:
schema_extra = {
"example": {
"id": 1,
"title": "Mi película",
"overview": "Descripción de la película",
"year": 2022,
"rating": 9.8,
"category" : "Acción"
}
}
movies = [
{
"id": 1,
"title": "Avatar",
"overview": "En un exuberante planeta llamado Pandora viven los Na'vi, seres que ...",
"year": "2009",
"rating": 7.8,
"category": "Acción"
},
{
"id": 2,
"title": "Avatar",
"overview": "En un exuberante planeta llamado Pandora viven los Na'vi, seres que ...",
"year": "2009",
"rating": 7.8,
"category": "Acción"
}
]
@app.get('/', tags=['home'])
def message():
return HTMLResponse('<h1>Hello world</h1>')
@app.post('/login', tags=['auth'])
def login(user: User):
if user.email == "admin@gmail.com" and user.password == "admin":
token: str = create_token(user.dict())
return JSONResponse(status_code=200, content=token)
@app.get('/movies', tags=['movies'], response_model=List[Movie], status_code=200, dependencies=[Depends(JWTBearer())])
def get_movies() -> List[Movie]:
return JSONResponse(status_code=200, content=movies)
@app.get('/movies/{id}', tags=['movies'], response_model=Movie)
def get_movie(id: int = Path(ge=1, le=2000)) -> Movie:
for item in movies:
if item["id"] == id:
return JSONResponse(content=item)
return JSONResponse(status_code=404, content=[])
@app.get('/movies/', tags=['movies'], response_model=List[Movie])
def get_movies_by_category(category: str = Query(min_length=5, max_length=15)) -> List[Movie]:
data = [ item for item in movies if item['category'] == category ]
return JSONResponse(content=data)
@app.post('/movies', tags=['movies'], response_model=dict, status_code=201)
def create_movie(movie: Movie) -> dict:
movies.append(movie)
return JSONResponse(status_code=201, content={"message": "Se ha registrado la película"})
@app.put('/movies/{id}', tags=['movies'], response_model=dict, status_code=200)
def update_movie(id: int, movie: Movie)-> dict:
for item in movies:
if item["id"] == id:
item['title'] = movie.title
item['overview'] = movie.overview
item['year'] = movie.year
item['rating'] = movie.rating
item['category'] = movie.category
return JSONResponse(status_code=200, content={"message": "Se ha modificado la película"})
@app.delete('/movies/{id}', tags=['movies'], response_model=dict, status_code=200)
def delete_movie(id: int)-> dict:
for item in movies:
if item["id"] == id:
movies.remove(item)
return JSONResponse(status_code=200, content={"message": "Se ha eliminado la película"})