How to protect Python source from modification

Magnus Lycka lycka at carmen.se
Wed Sep 14 08:48:00 EDT 2005


Frank Millman wrote:
> I have seen Twisted mentioned many times in this ng, but I have no idea
> what it actually does. Can someone tell me in simple terms what
> advantage it might give me over a multi-threaded socket server program.

More control. Less resource usage. Twisted also provides a very
flexible way of building network aware software which you will
appreciate if you ever consider using something else than sockets.

Using several process means using more memory, and inter process
communication isn't as fast as in-process communication. Using
threads is error prone and difficult to debug. There are also scaling
issues with threads in Python (but maybe not when most threads wait
for network connections).

Twisted is based on an event loop, just like GUI programs. But instead
of waiting for GUI events, such as button clicks, the Twisted app will
wait for network events, such as data received. With Twisted and
sockets, you write code that will implement handlers for such events.

A simple example is provided here:

#!/usr/bin/python
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

### Protocol Implementation

# This is just about the simplest possible protocol
class Echo(Protocol):
     def dataReceived(self, data):
         """As soon as any data is received, write it back."""
         self.transport.write(data)


def main():
     f = Factory()
     f.protocol = Echo
     reactor.listenTCP(8000, f)
     reactor.run()

if __name__ == '__main__':
     main()

You see? You just subclass Protocol and override the relevant
event handler, and get the thing going! The factory will create
an Echo instance for each socket connection.

The problem in Twisted is that functions in this single thread that
are run inside the event loop must be fast--just as the event
handlers in your GUI app. Twisted helps you achieve this. For
instance, there is the concept of deferred execution, (described
in a paper available at http://python.fyxm.net/pycon/papers/deferex/ )
but you might want to use a separate thread for things like database
queries etc.

There are a lot of other batteries included, check out the Twisted
documentation at
http://twistedmatrix.com/projects/twisted/documentation/

You have to ask other Twisted users about scalability, but I think
it will scale well beyond your needs.




More information about the Python-list mailing list