This commit is contained in:
Waylon Walker 2023-06-08 09:02:43 -05:00
parent a9ee4a2bd8
commit d68cda91cf
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
22 changed files with 824 additions and 55 deletions

View file

@ -2,8 +2,24 @@ from fastapi import FastAPI
from learn_sql_model.api.hero import hero_router
from learn_sql_model.api.user import user_router
from learn_sql_model.api.websocket import web_socket_router
# from fastapi_socketio import SocketManager
app = FastAPI()
# socket_manager = SocketManager(app=app)
app.include_router(hero_router)
app.include_router(user_router)
app.include_router(web_socket_router)
# @app.sio.on("join")
# def handle_join(sid, *args, **kwargs):
# app.sio.emit("lobby", "User joined")
# @app.sio.on("leave")
# def handle_leave(sid, *args, **kwargs):
# sm.emit("lobby", "User left")

View file

@ -4,8 +4,15 @@ from fastapi import APIRouter, Depends
from sqlmodel import SQLModel
from learn_sql_model.api.user import oauth2_scheme
from learn_sql_model.api.websocket_connection_manager import manager
from learn_sql_model.config import Config, get_config
from learn_sql_model.models.hero import Hero
from learn_sql_model.models.hero import (
Hero,
HeroCreate,
HeroDelete,
HeroRead,
HeroUpdate,
)
hero_router = APIRouter()
@ -21,30 +28,46 @@ async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
@hero_router.get("/hero/{id}")
def get_hero(id: int, config: Config = Depends(get_config)) -> Hero:
async def get_hero(id: int, config: Config = Depends(get_config)) -> Hero:
"get one hero"
return Hero().get(id=id, config=config)
@hero_router.get("/h/{id}")
def get_h(id: int, config: Config = Depends(get_config)) -> Hero:
async def get_h(id: int, config: Config = Depends(get_config)) -> Hero:
"get one hero"
return Hero().get(id=id, config=config)
@hero_router.post("/hero/")
def post_hero(hero: Hero, config: Config = Depends(get_config)) -> Hero:
async def post_hero(hero: HeroCreate) -> HeroRead:
"read all the heros"
hero.post(config=config)
config = get_config()
hero = hero.post(config=config)
await manager.broadcast({hero.json()}, id=1)
return hero
@hero_router.patch("/hero/")
async def patch_hero(hero: HeroUpdate) -> HeroRead:
"read all the heros"
config = get_config()
hero = hero.update(config=config)
await manager.broadcast({hero.json()}, id=1)
return hero
@hero_router.delete("/hero/{hero_id}")
async def delete_hero(hero_id: int):
"read all the heros"
hero = HeroDelete(id=hero_id)
config = get_config()
hero = hero.delete(config=config)
await manager.broadcast(f"deleted hero {hero_id}", id=1)
return hero
@hero_router.get("/heros/")
def get_heros(config: Config = Depends(get_config)) -> list[Hero]:
async def get_heros(config: Config = Depends(get_config)) -> list[Hero]:
"get all heros"
return Hero().get(config=config)
# Alternatively
# with get_config().database.session as session:
# statement = select(Hero)
# results = session.exec(statement).all()
# return results

View file

@ -0,0 +1,45 @@
from typing import Annotated
from fastapi import APIRouter, Depends
from sqlmodel import SQLModel
from learn_sql_model.api.user import oauth2_scheme
from learn_sql_model.config import Config, get_config
from learn_sql_model.models.new import new
new_router = APIRouter()
@new_router.on_event("startup")
def on_startup() -> None:
SQLModel.metadata.create_all(get_config().database.engine)
@new_router.get("/items/")
async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
return {"token": token}
@new_router.get("/new/{id}")
def get_new(id: int, config: Config = Depends(get_config)) -> new:
"get one new"
return new().get(id=id, config=config)
@new_router.get("/h/{id}")
def get_h(id: int, config: Config = Depends(get_config)) -> new:
"get one new"
return new().get(id=id, config=config)
@new_router.post("/new/")
def post_new(new: new, config: Config = Depends(get_config)) -> new:
"read all the news"
new.post(config=config)
return new
@new_router.get("/news/")
def get_news(config: Config = Depends(get_config)) -> list[new]:
"get all news"
return new().get(config=config)

View file

@ -0,0 +1,72 @@
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from learn_sql_model.api.websocket_connection_manager import manager
web_socket_router = APIRouter()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:5000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@web_socket_router.get("/watch")
async def get():
return HTMLResponse(html)
@web_socket_router.websocket("/ws/{id}")
async def websocket_endpoint_connect(websocket: WebSocket, id: int):
await manager.connect(websocket, id)
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"[gold]You Said: {data}")
await manager.broadcast(f"[blue]USER: {data}", id)
except WebSocketDisconnect:
manager.disconnect(websocket, id)
await manager.broadcast(f"Client #{id} left the chat", id)
@web_socket_router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"[blue]USER: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket, id)
await manager.broadcast(f"Client #{client_id} left the chat", id)

View file

@ -0,0 +1,41 @@
from typing import Dict
from fastapi import WebSocket
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, list[WebSocket]] = {}
async def connect(self, websocket: WebSocket, id: str):
print("connecting...", id)
if id not in self.active_connections:
self.active_connections[id] = []
await websocket.accept()
self.active_connections[id].append(websocket)
def disconnect(self, websocket: WebSocket, id: str):
if id not in self.active_connections:
return
self.active_connections[id].remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str, id: str):
if id not in self.active_connections:
return
print(f"i go this message {message}")
print(
f"I am going to send it to {len(self.active_connections[id])} connections"
)
for connection in self.active_connections[id]:
print("sending it to ", connection)
try:
await connection.send_text(message)
except Exception:
self.disconnect(connection, id)
print("sent it to ", connection)
manager = ConnectionManager()