Introduction
Before you start using threads, make sure you do at the start of your program:
from twisted.python import threadable threadable.init()
This will make certain parts of Twisted thread-safe so you can use them safely. However, note that most parts of Twisted are not thread-safe.
Running code in a thread-safe manner
Most code in Twisted is not thread-safe. For example,
writing data to a transport from a protocol is not thread-safe.
Therefore, we want a way to schedule methods to be run in the
main event loop. This can be done using the function So, you know what factories are, and want to run the QOTD
with configurable quote server, do you? No problems, here is an
example. The only lines you might not understand are the last two.factory.fp.write(line+'\n')
class LogfileFactory(Factory):
protocol = LoggingProtocol
def __init__(self, fileName):
self.file = fileName
def startFactory(self):
self.fp = open(self.file, 'a')
def stopFactory(self):
self.fp.close()
Putting it All Together
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
self.transport.write(self.factory.quote+'\r\n')
self.transport.loseConnection()
class QOTDFactory(Factory):
protocol = QOTD
def __init__(self, quote=None):
self.quote = quote or 'An apple a day keeps the doctor away'
reactor.listenTCP(8007, QOTDFactory("configurable quote"))
reactor.run()
listenTCP is
the method which connects a Factory to the network.
It uses the reactor interface, which lets many different loops handle
the networking code, without modifying end-user code, like this.
As mentioned above, if you want to write your code to be a production-grade
Twisted server, and not a mere 20-line hack, you will want to
use the Application object.