Problem:
Consider a scenario where you're building a commenting system on a blog. You're rendering existing comments using Jinja2 templates. When a new comment is posted via a FastAPI route, you need to update the list of comments displayed in the template.
Solution:
While Jinja2 is not ideal for handling real-time updates, a solution can be found using WebSockets. This requires modifying both the FastAPI backend and the Jinja2 template:
Example Code:
<code class="html"><!-- app.py --> @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: data = await websocket.receive_json() comments.append(Comment(data['author'], data['content'])) await manager.broadcast(data) except (WebSocketDisconnect, ConnectionClosed): manager.disconnect(websocket)</code>
<code class="html"><!-- index.html --> <script> var ws = new WebSocket("ws://localhost:8000/ws"); ws.onmessage = function(event) { var comments = document.getElementById('comments') var comment = document.createElement('li') var jsonObj = JSON.parse(event.data); var authorNode = document.createElement('h3'); authorNode.innerHTML = jsonObj.author; var contentNode = document.createElement('p'); contentNode.innerHTML = jsonObj.content; comment.appendChild(authorNode); comment.appendChild(contentNode); comments.appendChild(comment) }; function addComment(event) { var author = document.getElementById("author") var content = document.getElementById("content") ws.send(JSON.stringify({ "author": author.value, "content": content.value })) author.value = '' content.value = '' event.preventDefault() } </script></code>
By utilizing WebSockets, you can establish a real-time connection between the FastAPI backend and the Jinja2 template, allowing for the updated list of comments to be displayed in the UI.
The above is the detailed content of How to Update Comment List in Jinja2 Templates Using WebSockets with FastAPI?. For more information, please follow other related articles on the PHP Chinese website!