【发布时间】: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