Python Twisted client
-
13-10-2019 - |
Question
J'ai ce simple Twisted client qui se connecte à un serveur et torsadés interroge un index.
Si vous voyez fn. connectionMade()
dans class SpellClient
, le query
est codé en dur. Est-ce que pour des fins d'analyse. Comment peut-on transmettre cette requête à l'extérieur de cette classe?
Le 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()
La solution
Protocoles, comme SpellClient, ont accès à leur usine comme self.factory.
... donc il y aurait un certain nombre de façons de le faire, mais d'une façon serait de créer une autre méthode sur SpellFactory, comme setQuery, et d'accéder ensuite à partir du client ...
#...in SpellFactory:
def setQuery(self, query):
self.query = query
#...and in SpellClient:
def connectionMade(self):
self.transport.write(self.factory.query)
... donc dans le principal:
f = SpellFactory()
f.setQuery('some query')
...
... ou vous pouvez simplement créer un _ init _ méthode pour SpellFactory et passer là-bas.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow