[Twisted-Python] Help using XmlStreamFactory & XmlStream : XPathQuery error?
p.mayers at imperial.ac.uk
Thu Feb 21 06:31:40 EST 2008
>> One solution is to have a difference instance for each connection and
>> to use
>> a bound method as the event handler. This gives you an obvious
>> place to keep state and such - on the instance.
> Jean-Paul, sorry for the dumb question, when you mean a different
> instance, you mean a thread? What is a bound method? I'm fairly new to
> python and very new to twisted (as you can probably tell).
A bound method is a function on a class instance. e.g.:
>>> class A:
... def func(self):
>>> aa = A()
<unbound method A.func>
<bound method A.func of <__main__.A instance at 0x2aaaaab423b0>>
A.func is the unbound method - it's a function object, defined in the
class, but the class is not instantiated so it's unbound.
aa.func is a bound version of A.func - it's bound to the instance "aa"
and will fill in the "self" argument when called.
Think about it like this:
When you use 1 thread per connection, your "state" is usually stored as
local variables inside a function i.e. on the stack.
When you use 1 thread for all connections, your "state" needs to be
attached to the connection e.g. as instance variables of the protocol or
an attached object.
So, you might do this:
from twisted.protocols import basic
from twisted.internet import protocol, reactor
def lineReceived(self, line):
def connectionLost(self, reason):
print "my data was", '\n'.join(self.data)
protocol = MyProto
def buildProtocol(self, *pargs, **kwargs):
p = protocol.ServerFactory.buildProtocol(self, *pargs, **kwargs)
p.data = 
Relating to your other email - a similar technique works for more
complex things e.g.
def dataReceived(self, data):
p = ..
p.parser = XmlParser()
More information about the Twisted-Python