A quick introduction to Python's Twisted networking library, given at a NZPUG meeting in April 2009.
Covers some of the stuff you can do with Twisted really easily, like an XMPP bot and an SSH/Telnet shell into your running applications.
2. What?
http://twistedmatrix.com
“an event-driven networking engine
written in Python”
3. Networking?
• You name it, Twisted does it:
TCP, UDP, Telnet, SSH, SSL, HTTP, FTP,
SFTP, Gopher, XMPP, MSN, AIM, IRC,
Multicast, Unix, SMTP, LDAP, POP3,
NNTP, NTP, DNS...
4. Deferreds
• They’re the barrier to Twisted
• Single-threaded asynchronous programming
• A Deferred is a promise to call code later
• Not just a Python thing
6. Deferreds
from twisted.web.client import getPage
from twisted.internet import reactor
def printContents(contents):
'''
This is the 'callback' function, added to the Deferred and called by
it when the promised data is available
'''
print quot;The Deferred has called printContents with the following
contents:quot;
print contents
# Stop the Twisted event handling system -- this is usually handled
# in higher level ways
reactor.stop()
8. Servers
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
self.transport.write(quot;An apple a day keeps the doctor awayrnquot;)
self.transport.loseConnection()
# Next lines are magic:
factory = Factory()
factory.protocol = QOTD
# 8007 is the port you want to run under. Choose something >1024
reactor.listenTCP(8007, factory)
reactor.run()
9. Instant Messaging
• uses the Twisted Words project
• support for XMPP (Jabber) + AIM, ICQ,
MSN, IRC, …
• create a bot
• Wokkel makes it easier
10. Bot
• will connect to an XMPP server
• show itself as being online
• have a conversation with anybody who
talks to it
15. How to use?
• Live inspection rather than
trial & error debugging
• distributed apps - separate components
• any networking bridges, converters,
multi-purpose magic apps