首页  >  文章  >  后端开发  >  如何使用 FastAPI 在 Jinja2 中实现 WebSocket 进行实时数据更新?

如何使用 FastAPI 在 Jinja2 中实现 WebSocket 进行实时数据更新?

Barbara Streisand
Barbara Streisand原创
2024-10-21 06:12:30481浏览

How to Implement WebSockets for Real-Time Data Updates in Jinja2 with FastAPI?

如何使用 FastAPI 获取 Jinja2 模板中更新的项目列表?

在 Jinja2 模板中,您可以使用循环渲染现有数据,例如在博客文章。然而,当添加新项目时,Jinja2 本身并没有提供动态更新列表的方法。

使用 WebSocket 的潜在解决方案

Web 应用程序中实时更新的常见解决方案是使用 WebSocket。以下Python代码提供了一个WebSocket端点:

<code class="python">from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class ConnectionManager:
    def __init__(self):
        self.active_connections = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_json(message)

manager = ConnectionManager()</code>

在index.html模板中,我们建立一个WebSocket连接并监听传入消息:

<code class="html"><script>
  var ws = new WebSocket("ws://localhost:8000/ws");
  ws.onmessage = function(event) {
    // Handle new data and update UI accordingly
  };
</script></code>

然后WebSocket端点可以向连接的客户端广播任何更新。这允许实时动态显示更新的评论列表。

注意:

虽然 WebSockets 是此用例的可行解决方案,但考虑 Alpine JS 等替代方法也很重要x-for 循环或 ReactJS 用于更复杂的 UI 交互。

以上是如何使用 FastAPI 在 Jinja2 中实现 WebSocket 进行实时数据更新?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn