Goal
This document describes how to set up the TwistedQuotes application used in a number of other documents, such as designing Twisted applications.
Setting up the TwistedQuotes project directory
In order to run the Twisted Quotes example, you will need to do the following:
- Make a
TwistedQuotes
directory on your system - Place the following files in the
TwistedQuotes
directory:- (this file marks it as a package, see this section of the Python tutorial for more on packages);
"""Twisted Quotes."""
Source listing - listings/TwistedQuotes/__init__.py - ;
from zope.interface import Interface, implements from random import choice class IQuoter(Interface): """An object that returns quotes.""" def getQuote(): """Return a quote.""" class StaticQuoter: """Return a static quote.""" implements(IQuoter) def __init__(self, quote): self.quote = quote def getQuote(self): return self.quote class FortuneQuoter: """Load quotes from a fortune-format file.""" implements(IQuoter) def __init__(self, filenames): self.filenames = filenames def getQuote(self): return choice(open(choice(self.filenames)).read().split('\n%\n'))
Source listing - listings/TwistedQuotes/quoters.py - ; and
from twisted.internet.protocol import Factory, Protocol class QOTD(Protocol): def connectionMade(self): self.transport.write(self.factory.quoter.getQuote()+'\r\n') self.transport.loseConnection() class QOTDFactory(Factory): protocol = QOTD def __init__(self, quoter): self.quoter = quoter
Source listing - listings/TwistedQuotes/quoteproto.py - .
register("Quote of the Day TAP Builder", "TwistedQuotes.quotetap", description=""" Example of a TAP builder module. """, type="tap", tapname="qotd")
Source listing - listings/TwistedQuotes/plugins.tml
- Add the
TwistedQuotes
directory's parent to your Python path. For example, if the TwistedQuotes directory's path is/tmp/TwistedQuotes
add/tmp
to your Python path. On UNIX this would beexport PYTHONPATH=/my/stuff:$PYTHONPATH
, on Microsoft Windows change thePYTHONPATH
variable through the Systems Properites dialog to add/my/stuff;
at the beginning. -
Test your package by trying to import it in the Python interpreter:
Python 2.1.3 (#1, Apr 20 2002, 22:45:31) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import TwistedQuotes >>> # No traceback means you're fine.