Last active
May 28, 2025 17:31
-
-
Save edavidaja/dae1ba6521da01a2aafc96b3c79898a2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # adapted from | |
| # https://fastapi.tiangolo.com/advanced/websockets/#await-for-messages-and-send-messages | |
| import os | |
| from fastapi import FastAPI, WebSocket | |
| from fastapi.responses import HTMLResponse | |
| app = FastAPI() | |
| CONNECT_SERVER = os.getenv("CONNECT_SERVER") | |
| CONNECT_CONTENT_GUID = os.getenv("CONNECT_CONTENT_GUID") | |
| html = f""" | |
| <!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("{CONNECT_SERVER}content/{CONNECT_CONTENT_GUID}/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> | |
| """ | |
| @app.get("/") | |
| async def get(): | |
| return HTMLResponse(html) | |
| @app.websocket("/ws") | |
| async def websocket_endpoint(websocket: WebSocket): | |
| await websocket.accept() | |
| while True: | |
| data = await websocket.receive_text() | |
| await websocket.send_text(f"Message text was: {data}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| FastAPI | |
| websockets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment