Python Twisted Client

I have this simple Twisted Client that connects to a Twisted server and requests an index. If you see fn. connectionMade() in class SpellClient , query hard-coded. This was for testing purposes. How to pass this request from outside to this class?

Code -

 from twisted.internet import reactor from twisted.internet import protocol # a client protocol class SpellClient(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): query = 'abased' self.transport.write(query) def dataReceived(self, data): "As soon as any data is received, write it back." print "Server said:", data self.transport.loseConnection() def connectionLost(self, reason): print "connection lost" class SpellFactory(protocol.ClientFactory): protocol = SpellClient def clientConnectionFailed(self, connector, reason): print "Connection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "Connection lost - goodbye!" reactor.stop() # this connects the protocol to a server runing on port 8000 def main(): f = SpellFactory() reactor.connectTCP("localhost", 8090, f) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main() 
+4
source share
1 answer

Protocols such as SpellClient have access to their factory as self.factory.
... so there would be several ways to do this, but one way would be to create another SpellFactory method like setQuery and then access it from the client ...

 #...in SpellFactory: def setQuery(self, query): self.query = query #...and in SpellClient: def connectionMade(self): self.transport.write(self.factory.query) 

... therefore basically:

 f = SpellFactory() f.setQuery('some query') ... 

... or you can just create the _init_ method for SpellFactory and pass it there.

+5
source

Source: https://habr.com/ru/post/1333330/


All Articles