-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
126 lines (91 loc) · 3.73 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from fastapi import Depends, FastAPI, HTTPException, WebSocket, WebSocketDisconnect
from typing import Optional, List
from fastapi.middleware.cors import CORSMiddleware
import fastapi.security as security
import sql_app.models as model
import sql_app.schemas as schema
import sql_app.database as database
import sql_app.services as services
import sql_app.crud as crud
from WebSocket.connection import manager, generate_id
# source ./venv/bin/activate && uvicorn main:app --reload
# ./venv/Scripts/activate && uvicorn main:app --reload
# ./venv/Scripts/activate; uvicorn main:app --reload
# model.Base.metadata.create_all(bind=engine)
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:3000",
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
database.metadata.create_all(database.engine)
app.state.database = database.database
@app.on_event("startup")
async def startup() -> None:
database_ = app.state.database
if not database_.is_connected:
await database_.connect()
@app.on_event("shutdown")
async def shutdown() -> None:
database_ = app.state.database
if database_.is_connected:
await database_.disconnect()
@app.post("/users/")
async def create_user(user: schema.User):
db_user = await crud.get_user_by_nick(nick=user.nickname)
if db_user != None:
raise HTTPException(status_code=400, detail="Nick already registered")
db_user = await crud.create_user(user=user)
token = await services.create_token(db_user)
# return db_user
return token
@app.post("/messages/users", response_model=model.Message)
async def create_message_for_user(message: schema.Message, user: schema.User = Depends(services.get_current_user)):
res = await crud.create_user_message(message=message)
if res == None:
raise HTTPException(status_code=400, detail="User doesn't exists")
return res
@app.get("/users/all", response_model=List[schema.User])
async def read_users(user: schema.User = Depends(services.get_current_user)):
users = await crud.get_users()
return users
@app.get("/users/", response_model=schema.User)
async def read_user(user_id: Optional[int] = None, user_nick: Optional[str] = None, user: schema.User = Depends(services.get_current_user)):
if (user_id is None) and (user_nick is not None):
return await crud.get_user_by_nick(nick=user_nick)
elif (user_nick is None) and (user_id is not None):
return await crud.get_user(user_id=user_id)
else:
raise HTTPException(status_code=500, detail="Internal Server Error")
@app.get("/users/me", response_model=schema.User)
async def read_user(user: schema.User = Depends(services.get_current_user)):
return user
@app.get("/messages/", response_model=List[model.Message])
async def read_messages(user: schema.User = Depends(services.get_current_user)):
messages = await crud.get_messages()
return messages
@app.websocket("/ws/")
# async def websocket_endpoint(websocket: WebSocket, client_id: str = generate_id()):
async def websocket_endpoint(websocket: WebSocket, client_id: str = Depends(generate_id)):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(data, websocket)
except WebSocketDisconnect:
manager.disconnect(websocket)
@app.post("/api/token")
async def generate_token(
form_data: security.OAuth2PasswordRequestForm = Depends()
):
user = await services.authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=401, detail="Invalid Credentials")
return await services.create_token(user)