I am trying to set a class attribute basically redisconnection object once the connection is established to a variable in another class. I use setattr to set the variable. When i try to access the variable the value is null.
import importlib
import json
import sys
import time
import traceback
from twisted.python import log
import txredisapi
from settings import gcl_decorator_init
from twisted.internet import reactor
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
class TestLogger(object):
connectionObj = None
@classmethod
def log(cls, data):
connObject = getattr(TestLogger, "connectionObj")
print("connObject is : ",connObject)
cls.connectionObj.publish("TestChannel","DataNew")
class TestServiceProtocol(txredisapi.SubscriberProtocol):
def connectionMade(self):
conn = txredisapi.lazyConnection(host=REDIS_HOST, port=REDIS_PORT)
print("connected. and alive.",conn)
setattr(TestLogger, "connectionObj", conn)
print('value of CollectorService.connection : ',getattr(TestLogger,"connectionObj"))
def messageReceived(self, pattern, channel, message):
pass
def connectionLost(self, reason):
print("lost connection to the redis server, Reason : ", reason)
class TestServiceFactory(txredisapi.SubscriberFactory):
maxDelay = 120
continueTrying = True
protocol = TestServiceProtocol
class TestService(object):
manager = None
connection = None
@staticmethod
def initialize():
try:
svc = TestServiceFactory()
return svc
except Exception as ex:
log.msg("Exception {}".format(traceback.format_exc()))
log.msg("Failed to initialize service {}".format(ex))
time.sleep(5)
raise ex
if __name__ == '__main__':
svc = TestService.initialize()
reactor.connectTCP(REDIS_HOST, REDIS_PORT, svc)
reactor.run()
Below is the test program
from untitled import TestLogger
if __name__ == "__main__":
testLogger = TestLogger()
print("connection from object : ",getattr(testLogger,"connectionObj"))
TestLogger.log("Data")
Require help in identifying where i get wrong. Is classmethod is appropriate? Also throw suggestion if the way to access the object is wrong.