设置 TwistedQuotes 应用程序

目标

本文档介绍了如何设置 TwistedQuotes 应用程序,该应用程序在许多其他文档中使用,例如 设计 Twisted 应用程序

设置 TwistedQuotes 项目目录

为了运行 Twisted Quotes 示例,您需要执行以下操作

  1. 在您的系统上创建一个名为 TwistedQuotes 的目录

  2. 将以下文件放置在 TwistedQuotes 目录中

    • __init__.py

      """
      Twisted Quotes
      """
      

      (此文件将其标记为一个包,有关包的更多信息,请参阅 Python 教程的这一部分

    • quoters.py

      from random import choice
      
      from zope.interface import implementer
      
      from TwistedQuotes import quoteproto
      
      
      @implementer(quoteproto.IQuoter)
      class StaticQuoter:
          """
          Return a static quote.
          """
      
          def __init__(self, quote):
              self.quote = quote
      
          def getQuote(self):
              return self.quote
      
      
      @implementer(quoteproto.IQuoter)
      class FortuneQuoter:
          """
          Load quotes from a fortune-format file.
          """
      
          def __init__(self, filenames):
              self.filenames = filenames
      
          def getQuote(self):
              with open(choice(self.filenames)) as quoteFile:
                  quotes = quoteFile.read().split("\n%\n")
              return choice(quotes)
      
    • quoteproto.py

      from zope.interface import Interface
      
      from twisted.internet.protocol import Factory, Protocol
      
      
      class IQuoter(Interface):
          """
          An object that returns quotes.
          """
      
          def getQuote():
              """
              Return a quote.
              """
      
      
      class QOTD(Protocol):
          def connectionMade(self):
              self.transport.write(self.factory.quoter.getQuote() + "\r\n")
              self.transport.loseConnection()
      
      
      class QOTDFactory(Factory):
          """
          A factory for the Quote of the Day protocol.
      
          @type quoter: L{IQuoter} provider
          @ivar quoter: An object which provides L{IQuoter} which will be used by
              the L{QOTD} protocol to get quotes to emit.
          """
      
          protocol = QOTD
      
          def __init__(self, quoter):
              self.quoter = quoter
      
  3. TwistedQuotes 目录的目录添加到您的 Python 路径中。例如,如果 TwistedQuotes 目录的路径为 /mystuff/TwistedQuotesc:\mystuff\TwistedQuotes,请将 /mystuff 添加到您的 Python 路径中。在 UNIX 上,这将是 export PYTHONPATH=/mystuff:$PYTHONPATH,在 Microsoft Windows 上,通过系统属性对话框添加 ;c:\mystuff 到末尾来更改 PYTHONPATH 变量。

  4. 在 Python 解释器中尝试导入该包以测试您的包

    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.