Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
|
| 2 |
+
from fastapi.staticfiles import StaticFiles
|
| 3 |
+
from fastapi.templating import Jinja2Templates
|
| 4 |
+
from typing import List
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 8 |
+
|
| 9 |
+
templates = Jinja2Templates(directory="templates")
|
| 10 |
+
|
| 11 |
+
class ConnectionManager:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.active_connections: List[WebSocket] = []
|
| 14 |
+
|
| 15 |
+
async def connect(self, websocket: WebSocket):
|
| 16 |
+
await websocket.accept()
|
| 17 |
+
self.active_connections.append(websocket)
|
| 18 |
+
|
| 19 |
+
def disconnect(self, websocket: WebSocket):
|
| 20 |
+
self.active_connections.remove(websocket)
|
| 21 |
+
|
| 22 |
+
async def broadcast(self, message: str):
|
| 23 |
+
for connection in self.active_connections:
|
| 24 |
+
await connection.send_text(message)
|
| 25 |
+
|
| 26 |
+
manager = ConnectionManager()
|
| 27 |
+
|
| 28 |
+
@app.get('/')
|
| 29 |
+
async def get(request: Request):
|
| 30 |
+
return templates.TemplateResponse('index.html', {'request': request})
|
| 31 |
+
|
| 32 |
+
@app.websocket('/ws')
|
| 33 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 34 |
+
await manager.connect(websocket)
|
| 35 |
+
try:
|
| 36 |
+
while True:
|
| 37 |
+
data = await websocket.receive_text()
|
| 38 |
+
await manager.broadcast(data)
|
| 39 |
+
except WebSocketDisconnect:
|
| 40 |
+
manager.disconnect(websocket)
|