Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a websocket client as a class in python

I'm trying access some data using websockets, but I cannot really get around the examples given in the websockets documentation.

I have this code (https://pypi.org/project/websocket_client/) and want to transform it into a class.

import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open

    ws.run_forever()

The idea is to have this all websocket functionality in a class so that I can just create an object of that class.

I tried to start doing it but I cannot even get passed this:

class MySocket(object):
    def __init__(self):
        websocket.enableTrace(True)
        self.ws = websocket.WebSocketApp("ws://echo.websocket.org:12300/foo",
                                    on_message = on_message,
                                    on_error = on_error,
                                    on_close = on_close)

    def on_message(ws, message):
        print message

    def on_error(ws, error):
        print error

    def on_close(ws):
        print "### closed ###"

    def on_open(ws):
    ws.send("Hello %d" % i)

The error starts right away in on_message saying that's an "unresolved reference".

like image 801
jbssm Avatar asked Nov 17 '14 20:11

jbssm


People also ask

How does Python connect to WebSocket client?

WebSocket Client with PythonCreate a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.

Can you use WebSockets in Python?

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.

Can I use WebSockets FOR REST API?

REST is the most commonly used architecture for developing APIs in recent years. It supports a half-duplex data transmission between the client and server. In the case of full-duplex data transmission, WebSockets are used.


1 Answers

The WebSocketApp needs callable objects for its callbacks (both the ones you pass in the constructor, like on_message, and the one you're setting after the fact, on_open).

Plain functions are callable objects, so your non-OO version works fine, because you're passing the plain functions.

Bound methods are also callable objects. But your OO version isn't passing bound methods. A bound method is, as the name implies, bound to an object. You do this by using the obj.method notation. In your case, that's self.on_message:

self.ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                                 on_message = self.on_message,
                                 on_error = self.on_error,
                                 on_close = self.on_close)
self.ws.on_open = self.on_open

However, you've got another problem. While this will make your error go away, it won't make your code actually work. A normal method has to take self as its first argument:

def on_message(self, ws, message):
    print message

It's also worth noting that you're not really using the class for anything. If you never access anything off self, the class is just acting like a namespace. Not that this is always a bad thing, but it's usually a sign that you need to at least think through your design. Is there really any state that you need to maintain? If not, why do you want a class in the first place?

You may want to reread the tutorial section on Classes to understand about methods, self, etc.

like image 112
abarnert Avatar answered Nov 02 '22 22:11

abarnert