How to enable Javascript to communicate with Python 2.7 Bottle through WebSockets?

Environment

Python 2.7  
bottle==0.12.9  
gevent==1.1.2  
gevent-websocket==0.9.5
greenlet==0.4.10

Desired behavior

When executing the Bottle route from a getJSON()single user ’s request in the frontend of the website, I want to use WebSockets to send data back to update the div in front of the website, which is visible to all users.

Current behavior

After completing the following steps, I get Python errors from tail -100 /var/log/apache2/error.logthat end in:

[wsgi:error] [pid 8953:tid 140138351044352] [client 127.0.0.1:32820] LoopExit: ('This operation would block forever', <Hub at 0x7f746570d7d0 epoll default pending=0 ref=0 fileno=13 resolver=<gevent.resolver_thread.Resolver at 0x7f74656737d0 pool=<ThreadPool at 0x7f7465615210 0/1/10>> threadpool=<ThreadPool at 0x7f7465615210 0/1/10>>)

What i tried

I follow this official short bottle example to incorporate WebSocket functionality into an existing Python 2.7 Bottle application.

This is the corresponding Python code I have:

from bottle import route, post, default_app, template, view, TEMPLATE_PATH, response, request, static_file, install, redirect, abort

application=default_app()

@route('/websocket')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')

    while True:
        try:
            message = wsock.receive()
            wsock.send("Your message was: %r" % message)
        except WebSocketError:
            break

from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
server = WSGIServer(("127.0.0.1", 8080), application,
                    handler_class=WebSocketHandler)
server.serve_forever()

, :

from gevent import monkey, sleep
monkey.patch_all()

sudo systemctl restart apache2.service:

[wsgi:error] [pid 9252:tid 140619290474240] [client 127.0.0.1:33322] LoopExit: ('This operation would block forever', <Hub at 0x7fe45f274c30 epoll default pending=0 ref=0 fileno=13 resolver=<gevent.resolver_thread.Resolver at 0x7fe45f1bfa10 pool=<ThreadPool at 0x7fe45f18a110 0/1/10>> threadpool=<ThreadPool at 0x7fe45f18a110 0/1/10>>)

virtualenv :

pip install gevent
pip install gevent-websocket

Javascript

WebSockets , , .

$(document).on("click",".my_class, function () {
var ws = new WebSocket("ws://localhost:8080/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
});
+4

Source: https://habr.com/ru/post/1652044/


All Articles