wip
This commit is contained in:
parent
a70c24398a
commit
e181f57a91
30 changed files with 2458 additions and 197 deletions
22
htmx_patterns/websocket/dependencies.py
Normal file
22
htmx_patterns/websocket/dependencies.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
from fastapi import WebSocket
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Class defining socket events"""
|
||||
|
||||
def __init__(self):
|
||||
"""init method, keeping track of connections"""
|
||||
self.active_connections = []
|
||||
|
||||
async def connect(self, websocket: WebSocket):
|
||||
"""connect event"""
|
||||
await websocket.accept()
|
||||
self.active_connections.append(websocket)
|
||||
|
||||
async def send_personal_message(self, message: str, websocket: WebSocket):
|
||||
"""Direct Message"""
|
||||
await websocket.send_text(message)
|
||||
|
||||
def disconnect(self, websocket: WebSocket):
|
||||
"""disconnect event"""
|
||||
self.active_connections.remove(websocket)
|
||||
39
htmx_patterns/websocket/router.py
Normal file
39
htmx_patterns/websocket/router.py
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
|
||||
from htmx_patterns.websocket.dependencies import ConnectionManager
|
||||
|
||||
from htmx_patterns.config import get_config
|
||||
|
||||
|
||||
websocket_router = APIRouter(prefix="/websocket", tags=["Websocket"])
|
||||
|
||||
manager = ConnectionManager()
|
||||
|
||||
config = get_config()
|
||||
|
||||
|
||||
@websocket_router.get("/")
|
||||
def websocket_index(request: Request):
|
||||
return config.templates.TemplateResponse(
|
||||
"websocket/index.html", {"request": request}
|
||||
)
|
||||
|
||||
|
||||
@websocket_router.websocket("/")
|
||||
async def websocket_endpoint(
|
||||
websocket: WebSocket,
|
||||
):
|
||||
await manager.connect(websocket)
|
||||
await manager.send_personal_message("Hello", websocket)
|
||||
try:
|
||||
while True:
|
||||
data = await websocket.receive_text()
|
||||
await manager.send_personal_message(f"Received:{data}", websocket)
|
||||
# import time
|
||||
#
|
||||
# time.sleep(1)
|
||||
# data = "hello"
|
||||
# await manager.send_personal_message(f"Received:{data}", websocket)
|
||||
#
|
||||
except WebSocketDisconnect:
|
||||
manager.disconnect(websocket)
|
||||
await manager.send_personal_message("Bye!!!", websocket)
|
||||
Loading…
Add table
Add a link
Reference in a new issue