setattribute для classvariable - PullRequest
       36

setattribute для classvariable

0 голосов
/ 09 января 2019

Я пытаюсь установить атрибут класса в основном объект повторного подключения, как только соединение установлено с переменной в другом классе. Я использую setattr для установки переменной. Когда я пытаюсь получить доступ к переменной, значение равно нулю.

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()

Ниже приведена тестовая программа

from untitled import TestLogger

if __name__ == "__main__":
    testLogger = TestLogger()
    print("connection from object : ",getattr(testLogger,"connectionObj"))
    TestLogger.log("Data")

Требуется помощь в определении, где я ошибаюсь. Подходит ли метод класса? Также выдвиньте предложение, если путь к объекту неправильный.

...