How to Update Comment List in Jinja2 Templates Using WebSockets with FastAPI?

Linda Hamilton
Release: 2024-10-21 06:15:30
Original
770 people have browsed it

How to Update Comment List in Jinja2 Templates Using WebSockets with FastAPI?

How to Get the Updated List of Items in Jinja2 Template Using FastAPI?

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:

FastAPI Backend (app.py):

  • Create a ConnectionManager class to manage WebSocket connections.
  • Define a send_personal_message method to send messages to specific clients.
  • Define a broadcast method to send messages to all connected clients.
  • Update the / route to handle connections and pass the comments list to the template.
  • Create a WebSocket endpoint (/ws) to handle incoming WebSocket connections and broadcast new comments.

Jinja2 Template (index.html):

  • Add a
      element to display the comments.
    • Create a JavaScript function addComment to send new comments via WebSocket.
    • In the onmessage event handler for the WebSocket, create HTML elements to display the new comment and append it to the
        element.

      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>
      Copy after login
      <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>
      Copy after login

      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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!