-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
68 lines (46 loc) · 2.02 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
from db.user_db import UserInDB
from db.user_db import update_user, get_user
from db.transaction_db import TransactionInDB
from db.transaction_db import save_transaction
from models.user_models import UserIn, UserOut
from models.transaction_models import TransactionIn, TransactionOut
import datetime
from fastapi import FastAPI, HTTPException
api = FastAPI()
from fastapi.middleware.cors import CORSMiddleware
origins = [
"http://localhost.tiangolo.com", "https://localhost.tiangolo.com",
"http://localhost", "http://localhost:8081","https://cajero-api-george.herokuapp.com",
]
api.add_middleware(
CORSMiddleware, allow_origins=origins,
allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
)
@api.post("/user/auth/")
async def auth_user(user_in: UserIn):
user_in_db = get_user(user_in.username)
if user_in_db == None:
raise HTTPException(status_code=404, detail="El usuario no existe")
if user_in_db.password != user_in.password:
return {"Autenticado": False}
return {"Autenticado": True}
@api.get("/user/balance/{username}")
async def get_balance(username: str):
user_in_db = get_user(username)
if user_in_db == None:
raise HTTPException(status_code=404, detail="El usuario no existe")
user_out = UserOut(**user_in_db.dict())
return user_out
@api.put("/user/transaction/")
async def make_transaction(transaction_in: TransactionIn):
user_in_db = get_user(transaction_in.username)
if user_in_db == None:
raise HTTPException(status_code=404, detail="El usuario no existe")
if user_in_db.balance < transaction_in.value:
raise HTTPException(status_code=400, detail="No se tienen los fondos suficientes")
user_in_db.balance = user_in_db.balance - transaction_in.value
update_user(user_in_db)
transaction_in_db = TransactionInDB(**transaction_in.dict(), actual_balance = user_in_db.balance)
transaction_in_db = save_transaction(transaction_in_db)
transaction_out = TransactionOut(**transaction_in_db.dict())
return transaction_out