简体   繁体   English

如何在没有 html/js 的情况下捕获 fastapi websocket 消息?

[英]How can I capture fastapi websocket messages without html/js?

Fastapi docs include a websocket example that receives data via html/javascript. Fastapi 文档包括一个通过 html/javascript 接收数据的websocket 示例 Saving the script as main.py and running uvicorn main:app --reload , the example works as expected:将脚本保存为main.py并运行uvicorn main:app --reload ,该示例按预期工作:

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

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}")

How can I modify this example to write websocket messages to file without using any html/js?如何修改此示例以在不使用任何 html/js 的情况下将 websocket 消息写入文件? I'd like direct access to the incoming data (text/json) with python and I'm unable to capture it directly.我想使用 python 直接访问传入数据(文本/json),但我无法直接捕获它。 Any additional info/clarity is appreciated.任何额外的信息/清晰度表示赞赏。

So, probably in the comments I didn't explain myself well.所以,可能在评论中我没有很好地解释自己。

From what I understood you want to connect via python to your webserver with a websocket and log to file the messages the server sends to your python script on the client.据我了解,您想通过 python 使用 websocket 连接到您的网络服务器,并记录服务器发送到客户端上 python 脚本的消息以归档。 In simpler terms, you need to mimic the html/js part via python.简单来说,您需要通过 python 来模仿 html/js 部分。

TL;DR TL;博士

The server is already there, you just need to connect to it.服务器已经在那里,您只需要连接到它。

Here's the code snippet that you have to copy and paste in a different file and run when the webserver is already running.这是您必须复制并粘贴到不同文件中并在网络服务器已经运行时运行的代码片段。 Note that the webserver doesn't need to be changed, if not for the two line within the while True loop.请注意,如果不是while True循环中的两行,则不需要更改网络服务器。 These can go away and you may change them with something like await websocket.send_text("text")这些可以 go 离开,你可以用await websocket.send_text("text")

import asyncio
import websockets


async def hello():
    uri = "ws://localhost:8000/ws"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello world!")
        res = await websocket.recv()
        print(res)

asyncio.get_event_loop().run_until_complete(hello())

I'm not sure what messages you need to write to file, but the code snippet above is working and is the basis for what you need.我不确定您需要将哪些消息写入文件,但上面的代码片段正在运行,并且是您需要的基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM