【问题标题】:How to get the "lastEventId" from fastapi websocket answer?如何从 fastapi websocket 答案中获取“lastEventId”?
【发布时间】:2021-03-08 11:45:22
【问题描述】:

我想从 fastapi 的 websocket 答案中获取“lastEventId”。在浏览器中检查代码时,我看到返回的对象有一个字段“lastEventId”,但不幸的是它是空的。有谁知道如何获得这个变量? (代码来源于fastapi网页上的示例代码,需要在pip install websocket前提下运行)

from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import re
from icecream import ic

app = FastAPI()


html = """

<!DOCTYPE html>
<html>
    <head>
        <title>A Form</title>
    </head>
    <body>
        <h1>WebSocket Form</h1>
        <form name="testform" action="" onsubmit="" onKeyUp="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off" placeholder="text" />
            <span id="texterror"></span>
            <button>Send</button>
        </form>
        
        <script>
            var ws = new WebSocket("ws://localhost:8000/ws");
            ws.onmessage = function(event) {
                console.log("answer from fastapi websocket: ",event)
                //the following variable is always null
                var field = document.getElementById(event.lastEventId)
                console.log("the find the last element: ", field);
            };

            function sendMessage(event) {

                // event.srcElemt.id because the final form shall have more inputs
                var input = document.getElementById(event.srcElement.id);
                console.log("value of following element to fastapi websocket: ",input);
                ws.send(input.value)
            }

        </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:
        ic(websocket.__dict__)
        data = await websocket.receive_text()
        print('"'+data+'"')
        await websocket.send_text(data)

【问题讨论】:

    标签: javascript python websocket fastapi


    【解决方案1】:

    我认为您可能将 WebSockets 误认为是 Server-Sent-Events

    服务器发送事件与 WebSockets https://www.html5rocks.com/en/tutorials/eventsource/basics/#toc-introduction-differences

    服务器发送的事件具有 WebSockets 在设计上缺乏的各种功能,例如自动重新连接、事件 ID 和发送任意事件的能力。

    Is there any ID for data chunks in WebSocket like lastEventId? 中提出了类似的问题

    【讨论】:

    • 请添加解释以提高洞察力并为 OP 提供更多信息
    • 我确实在此处包含了答案的基本部分,并且我引用了另一个 StackOverflow 问题以提供更多信息。
    猜你喜欢
    • 2023-03-20
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多