Rtucan
Rtucan

Reputation: 157

How to implement websocket inside a class?

I'm trying to use websocket.WebSocketApp inside a class so I could later on use the data retrieved from the websocket:

import requests
from urlparse import (urlparse, parse_qs)
import json
import websocket

class NeuroStream:

    def __init__(self, sensor, token):
    self._sensor = sensor
    self.token = token
    self.buf = []
    return

    def stream(self):
        self.ws = websocket.WebSocketApp(
            "wss://api.foofoo.com/api/v1/features/" + self._sensor
            + "/real-time/?all=true&access_token=" + self.token,
            on_message=self.on_message,
            on_error=self.on_error,
            on_close=self.on_close)
        self.ws.run_forever()

    def on_error(self, error):
        print(error)

    def on_close(self):
        print "connection lost"

    def on_message(self, message):
        message = json.loads(message)
        biomarkers = message[u'features']
        c1 = biomarkers[u'c1']
        self.buf.append(c1)

When I define the functions on_error, on_close and on_message outside the class's scope, replace the self with ws and omit the self from their calls, it works. But then I cannot use

self.buf.append(c1)  

Which is key for later uses

Edit: The code I'm running before the error, and also before the case that works:

from NeuroStream import *
ns = NeuroStream('a_sensor', 'a_token')
ns.stream()

The error I get is:

'No handlers could be found for logger "websocket"'

I saw a similar thread, but it didn't help: Using a websocket client as a class in python

Upvotes: 1

Views: 1371

Answers (1)

Anil_M
Anil_M

Reputation: 11463

I observed two issues.

1) "wss://api.foofoo.com/api/v1/features/" + self.sensor should be "wss://api.foofoo.com/api/v1/features/" + self._sensor since you have defined self._sensor = sensor during initialization.

2) Looks like you are trying to use client side feature of websocket library. Try installing websocket-client as below and then re-run the code.
pip install websocket-client

Code is working for me with above two changes.

Python 2.7.14 (default, Mar 22 2018, 14:43:05) 
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from aam import NeuroStream
>>> ns = NeuroStream('a_sensor', 'a_token')
>>> ns.stream()
>>>

Upvotes: 1

Related Questions