pythonasyncioapiasyncfastapiframeworkjsonjson-schemaopenapiopenapi3pydanticpython-typespython3redocreststarletteswaggerswagger-uiuvicornweb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.4 KiB
52 lines
1.4 KiB
from fastapi import FastAPI
|
|
from starlette.responses import HTMLResponse
|
|
from starlette.websockets import WebSocket
|
|
|
|
app = FastAPI()
|
|
|
|
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:8000/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}")
|
|
|