Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
Quart, chat server example

I am trying to make a quart application using multiple websockets at the same time:

<script type="text/javascript">
         let socket = new WebSocket('ws://localhost:5000/mensagens/{{ dialog_id }}');
         socket.onmessage = function(event) {
                  var messages_dom = document.getElementsByTagName('ul')[0];
                  var message_dom = document.createElement('li');
                  var cotent_dom = document.createTextNode(event.data);
                  message_dom.appendChild(cotent_dom);
                  messages_dom.appendChild(message_dom);
         };
</script>

<script>
         let ws = new WebSocket('ws://localhost:5000/printar/12');
         function myFunction() {
                  var x = document.getElementById("myText").value;
                  ws.send(x);
                  document.getElementById("demo").innerHTML = x;
    };
</script>

And this is the server side:

#Quart
from quart import Quart, render_template, url_for, websocket, redirect, request

#asyncio
import asyncio

app = Quart(__name__)

...
#websocket da conversa individual
@app.websocket('/mensagens/<dialog_id>')
async def mensagens(dialog_id):
         print("123");
         try:
                  output = await ".....function that updates from the SQLite database....";
                  await websocket.send(f"{output}");
         
         await asyncio.sleep(1);

         except Exception as e:
                  print("-------");
                  print(e);

#websocket de enviar mensagens
@app.websocket('/printar/<dialog_id>')
async def printar(dialog_id):
         print("aqui");
         try:         
                  while True:
                           print(dialog_id);
                           data = await websocket.receive();
                           print(data + "\n=====");

         except Exception as e:
                  print(e);


if __name__ == "__main__":
    try:
        app.run();

    except KeyboardInterrupt:
        print("=====\nAdeus!\n=====");

    except Exception as e:
        print(e);

However, for some reason, the second websocket only begin to run after the first websocket receives an update from "mensagens". I really don't understand what and why is happening.

Is there an example of a chat server made with Quart that I could look at?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So... I am idiot. I just found this where explains the user of receive and send indepedently (also, I am not that good with asyncio).

Anyway, here is an example:

<!doctype html>
<html>
  <head>
    <title>Quart + SQLite</title>
  </head>
  <body>
  <h1>Testes!</h1>

  <div class="mensagens">
     <ul></ul>
  </div>

  Mensagem: <input type="text" id="myText" value="Mickey">

  <p>Escreva suas mensagens acima!</p>

  <button onclick="myFunction()">Enviar</button>

  <p id="demo"></p>

  <script>
  let socket = new WebSocket('ws://localhost:5000/ws/12');
  function myFunction() {
    var x = document.getElementById("myText").value;
    socket.send(x);
    document.getElementById("demo").innerHTML = x;
  };

  socket.onmessage = function(event) {
    var messages_dom = document.getElementsByTagName('ul')[0];
    var message_dom = document.createElement('li');
    var cotent_dom = document.createTextNode(event.data);
    message_dom.appendChild(cotent_dom);
    messages_dom.appendChild(message_dom);
  };
  </script>

  </body>
</html>

And here is the python side:

#https://pgjones.gitlab.io/quart/how_to_guides/websockets.html
#Quart
from quart import Quart, render_template, url_for, websocket, redirect, request
import asyncio

app = Quart(__name__)

async def sending():
    while True:
        await websocket.send('f{1}');
        asyncio.sleep(1);

async def receiving():
    while True:
        data = await websocket.receive();
        print(data + "\n=====");
        
        

@app.websocket('/ws/<num>')
async def ws(num):
    print(num);
    producer = asyncio.create_task(sending());
    consumer = asyncio.create_task(receiving());
    await asyncio.gather(producer, consumer);

@app.route('/')
async def main():
    return await render_template('teste_html.html');


if __name__ == '__main__':
    try:
        app.run();

    except KeyboardInterrupt:
        print("=====\nAdeus!\n=====");

    except Exception as e:
        print(e);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda