O
O
onlygetc2021-10-16 14:57:55
Python
onlygetc, 2021-10-16 14:57:55

The task is next. With the use of FastApi it is necessary to make a web page combining from?

The task is next. Using FastApi, you need to make a web page that combines:
1. Forms with a text field
2. List of messages numbered from 1
The page connects to the server via WebSocket.
Using the form, you can send a message to the server, where it will be accepted and the serial number of this message will be added.
Next, a message with a serial number is sent to the page and displayed in the list.
When the page is reloaded, the numbering data is lost and starts from 1.
The page must be dynamic, handle all actions without reloading. This means that when sending a message to the server via a websocket, the page should not be reloaded.
Interaction with the server via websocket must be implemented using JSON. The format and naming of the fields is not important. you can use any.

I tried to implement, but I don’t know how the interaction with the server should look like

from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Задание</title>
    </head>
    <body>
        <h1>Сообщения</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Отправить</button>
        </form>
        <ol id='messages'>
        </ol>
        <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"{data}")

616abe0b9e841895903487.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question