1

i have edited this way:

my curl command is:

curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:5000/telepath

i want to display this posted data on every clients. i grabed what i can on documentation but it s not easy for me.

here is my script:

from quart import Quart, render_template, websocket
from functools import partial, wraps
from quart import request, redirect, url_for, copy_current_websocket_context
import asyncio

app = Quart(__name__)

connected_websockets = set()

def collect_websocket(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        global connected_websockets
        queue = asyncio.Queue()
        connected_websockets.add(queue)
        try:
            return await func(queue, *args, **kwargs)
        finally:
            connected_websockets.remove(queue)
    return wrapper

async def broadcast(message):
    for queue in connected_websockets:
        await queue.put(message)

@app.route('/')
async def index():
    return await render_template('index.html')


@app.websocket('/ws')
@collect_websocket
async def ws(queue):
    print("$ $ $",queue)
    while True:
        data = await websocket.receive()
        print("\n {}".format(data))
        await websocket.send(f"echo {data}")



@app.route('/telepath', methods=['POST'])
async def telepath():
    global connected_websockets    
    data = await request.get_json()
    for queue in connected_websockets:
        await queue.put(data["key1"])
    return "\n Request Processed.\n"



if __name__ == '__main__':
    app.run(port=5000)

and the template:

<!doctype html>
<html>
  <head>
    <title>My TEST</title>
  </head>
  <body>
    <input type="text" id="message">
    <button>Send</button>
    <ul></ul>
    <script type="text/javascript">
      var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/ws');
      ws.onmessage = function (event) {
        var messages_dom = document.getElementsByTagName('ul')[0];
        var message_dom = document.createElement('li');
        var content_dom = document.createTextNode('Received: ' + event.data);
        message_dom.appendChild(content_dom);
        messages_dom.appendChild(message_dom);
      };

      var button = document.getElementsByTagName('button')[0];
      button.onclick = function() {
        var content = document.getElementsByTagName('input')[0].value;
        ws.send(content);
      };


    document.addEventListener('DOMContentLoaded', function() {
    var es = new EventSource('/telepath');
    es.onmessage = function (event) {
        var messages_dom = document.getElementsByTagName('ul')[0];
        var message_dom = document.createElement('li');
        var content_dom = document.createTextNode('Received: ' + event.data);
        message_dom.appendChild(content_dom);
        messages_dom.appendChild(message_dom);
      };

    
    });


    let socket = new WebSocket("ws://localhost:5000/ws");

    socket.onmessage = function(event) {
        alert(`Data received: ${event.data}`);
        
    };

    
    
    </script>
  </body>
</html>

My final goal would be authentication, and to target who can receive private message from the server.

Impossible to transmitt the posted data via curl on mozilla or chrome client.

laticoda
  • 100
  • 14

1 Answers1

2

In your collect_websocket decorator you pass a queue argument to the websocket handler (return await func(queue, *args, **kwargs)) whereas your websocket handler accepts no arguments (async def ws()). This results in the error you see.

It looks like your ws_v2 websocket handler is setup to work with the collect_websocket decorator (async def ws_v2(queue)), so I think you can just switch to using that and rewrite the telepath as so,

@app.route('/telepath', methods=['POST'])
async def telepath():
    global connected_websockets    
    data = await request.get_json()
    for queue in connected_websockets:
        await queue.put(data["key1"])
return {}

Note you don't need to create any queues in the /telepath route as this is done by your collect_websocket decorator and also as you need a queue per websocket connection. You also don't need to await the ws_v2 handler, it will instead be called whenever there is a new websocket connection.

For the authentication I recommend you start with Quart-Auth (I am the author of the library).


Edit: Full code as requested,

import asyncio
from functools import partial, wraps

from quart import (
    copy_current_websocket_context, Quart, render_template, 
    request, websocket
)

app = Quart(__name__)

connected_websockets = set()

def collect_websocket(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        global connected_websockets
        queue = asyncio.Queue()
        connected_websockets.add(queue)
        try:
            return await func(queue, *args, **kwargs)
        finally:
            connected_websockets.remove(queue)
    return wrapper

async def broadcast(message):
    global connected_websockets 
    for queue in connected_websockets:
        await queue.put(message)

@app.route('/')
async def index():
    return await render_template('index.html')

@app.websocket('/ws')
@collect_websocket
async def ws(queue):
    await websocket.accept()
    while True:
        data = await queue.get()
        await websocket.send_json(data)

@app.route('/telepath', methods=['POST'])
async def telepath():   
    data = await request.get_json()
    await broadcast(data)
    return {}

if __name__ == '__main__':
    app.run(port=5000)

and the template,

<!doctype html>
<html>
  <head>
    <title>My TEST</title>
  </head>
  <body>
    <ul></ul>
    <script type="text/javascript">
      var ws = new WebSocket('ws://' + document.domain + ':' + location.port + '/ws');
      ws.onmessage = function (event) {
        const messagesDOM = document.getElementsByTagName('ul')[0];
        const messageDOM = document.createElement('li');
        const message = JSON.parse(event.data).message;
        const contentDOM = document.createTextNode('Received: ' + message);
        messageDOM.appendChild(contentDOM);
        messagesDOM.appendChild(messageDOM);
      };
    </script>
  </body>
</html>

Which then works with curl,

curl -H "content-type: application/json" -d '{"message": "Hello"}' localhost:5000/telepath

Note that the server will send all the JSON data it receives to the client, but the client only uses the message key.

pgjones
  • 6,044
  • 1
  • 14
  • 12
  • could you give full detailed working example please, i offer 100 points bounty ;-) – laticoda Oct 31 '20 at 12:58
  • Yep, I've just added the full detailed working example. It allows you to post to the /telepath route that is then sent to the connected clients. – pgjones Nov 01 '20 at 16:24