Firstly, I'm new to python and OOP so I'm still learning how things work.
I am trying to port a websocket API helper to a new websocket library as the original library has bugs and the github repo is inactive. The new library(autobahn-twisted) is asynchronous and works via callbacks, where the original library placed new responses onto a queue for synchronous processing. This adds another level of complexity that I am still learning.
Currently, there are 3 modules that I have created/modified. These are:
- connector.py
- contains Protocol class which extends WebsocketClientProtocol
- Protocol handles low level interaction with API such as formatting messages for sending, and receiving and processing(low lvl) responses
- client.py
- contains Client class which extends Protocol
- Client contains higher level functions for un/subscribing to streams, and accessing other API endpoints
- user_code.py
- contains userClass class
- my initial design was going to have this module inheriting from Client to perform operations on, and process the response data
My problem is in the userClass class, and its interaction with the other classes. I want to be able to call userClass methods from inside the Protocol class when messages are received and processed, and call Client methods from the userClass to request messages and subscribe to streams.
For the first attempt, I created an abstract class containing all the methods I wanted to call, and used userClass to implement all of them. This (I think) meant I could safely call the child methods from the parent methods, but I could not call the Client methods from userClass without creating a circular reference, and it seemed fragile(or in other words, everything broke) when I moved things to a new module.
My second attempt had Client as an object in userClass, using the aggregation relationship. Inside Client and Protocol, I referenced the userCode class rather than the object, however I then lose references to the object when calling methods.
I have not yet attempted to use straight inheritance with userClass inheriting Client and overwriting "dummy" methods from the parent classes, as it seemed like there was a lot of code duplication.
This example shows the functionality that I would like
class Protocol(WebsocketClientProtocol)
def onOpen(self):
print("open")
connectionOpened()
def send(self, msg):
self.sendMessage(json.dumps(msg))
class Client(Protocol)
def subscribe(self, msg)
self.send("subscribe_" + msg)
class userClass(Client)
def connectionOpened(self):
subscribe("this_stream")
What design paradigm should I follow to get this behaviour?
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire