Home >Backend Development >Python Tutorial >How to Implement WebSockets for Real-Time Data Updates in Jinja2 with FastAPI?
In Jinja2 templating, you can render existing data using loops, such as displaying comments on a blog post. However, when new items are added, Jinja2 doesn't natively provide a way to update the list dynamically.
A common solution for real-time updates in web applications is to use WebSockets. The following Python code provides a WebSocket endpoint:
<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>
In the index.html template, we establish a WebSocket connection and listen for incoming messages:
<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>
The WebSocket endpoint can then broadcast any updates to connected clients. This allows for a real-time and dynamic display of the updated comments list.
While WebSockets are a viable solution for this use case, it's important to consider alternative approaches like Alpine JS x-for loops or ReactJS for more complex UI interactions.
The above is the detailed content of How to Implement WebSockets for Real-Time Data Updates in Jinja2 with FastAPI?. For more information, please follow other related articles on the PHP Chinese website!