How to separate two different phases of a protocol in Twisted?

I am trying to learn how to do things with Twisted, and I am a bit stuck in one concept: creating a protocol that basically involves two separate steps: first a short handshake and authentication, and then the actual work.

My naive approach is to write such a protocol:

def stringReceived(self, data):
    if self.state == "authenticate":
        handle_auth(data)
    else:
        handle_actual_work(data)

It’s hard for me to figure out how to do this. Is this normal? It seems to me that it would be much more reasonable to write one protocol that performs authentication, and the other only with authenticated clients, but how exactly will I do it?

I looked at a similar Twisted question : how can I determine the protocol at the initial connection and then delegate the appropriate protocol implementation? . The solution given there comes down to the same as my current approach. Is this really the right approach?

+3
source share
1 answer

, . , Twisted , 100 , .. , : Twisted , ( stringReceived). , , , if - :).

" ", , , Python , . , , :

def stringReceived(self, data):
    getattr(self, "stringReceived_{}".format(self.state))(data)

def stringReceived_authenticate(self, data):
    if self.auth_ok(data):
       self.state = 'normal'
    else:
       self.transport.loseConnection()

def stringReceived_normal(self, data):
    self.do_stuff(data)

... , , , - . .

+3

All Articles