python - Twisted Python 接口(interface)实例是否可以不实现该接口(interface)的所有功能?

标签 python twisted

因为我正在查看此 blog 中的示例,我发现当作为 PoetryClientFactory 的参数的 ClientFactory 实例或作为 PoetryProtocol 的参数的 Protocol 实例未实现为 ClientFactory 或 Protocol 接口(interface)定义的所有功能时。 ClientFactory接口(interface)实现了startedConnecting、clientConnectionFailed和clientConnectionLost,但PoetryClientFactory没有实现startedConnecting和clientConnectionLost。怎么了?

# This is the Twisted Get Poetry Now! client, version 2.0.

# NOTE: This should not be used as the basis for production code.

import datetime, optparse

from twisted.internet.protocol import Protocol, ClientFactory


def parse_args():
    usage = """usage: %prog [options] [hostname]:port ...

This is the Get Poetry Now! client, Twisted version 2.0.
Run it like this:

  python get-poetry.py port1 port2 port3 ...

If you are in the base directory of the twisted-intro package,
you could run it like this:

  python twisted-client-2/get-poetry.py 10001 10002 10003

to grab poetry from servers on ports 10001, 10002, and 10003.

Of course, there need to be servers listening on those ports
for that to work.
"""

    parser = optparse.OptionParser(usage)

    _, addresses = parser.parse_args()

    if not addresses:
        print parser.format_help()
        parser.exit()

    def parse_address(addr):
        if ':' not in addr:
            host = '127.0.0.1'
            port = addr
        else:
            host, port = addr.split(':', 1)

        if not port.isdigit():
            parser.error('Ports must be integers.')

        return host, int(port)

    return map(parse_address, addresses)


class PoetryProtocol(Protocol):

    poem = ''
    task_num = 0

    def dataReceived(self, data):
        self.poem += data
        msg = 'Task %d: got %d bytes of poetry from %s'
        print  msg % (self.task_num, len(data), self.transport.getPeer())

    def connectionLost(self, reason):
        self.poemReceived(self.poem)

    def poemReceived(self, poem):
        self.factory.poem_finished(self.task_num, poem)


class PoetryClientFactory(ClientFactory):

    task_num = 1

    protocol = PoetryProtocol # tell base class what proto to build

    def __init__(self, poetry_count):
        self.poetry_count = poetry_count
        self.poems = {} # task num -> poem

    def buildProtocol(self, address):
        proto = ClientFactory.buildProtocol(self, address)
        proto.task_num = self.task_num
        self.task_num += 1
        return proto

    def poem_finished(self, task_num=None, poem=None):
        if task_num is not None:
            self.poems[task_num] = poem

        self.poetry_count -= 1

        if self.poetry_count == 0:
            self.report()
            from twisted.internet import reactor
            reactor.stop()

    def report(self):
        for i in self.poems:
            print 'Task %d: %d bytes of poetry' % (i, len(self.poems[i]))

    def clientConnectionFailed(self, connector, reason):
        print 'Failed to connect to:', connector.getDestination()
        self.poem_finished()


def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    factory = PoetryClientFactory(len(addresses))

    from twisted.internet import reactor

    for address in addresses:
        host, port = address
        reactor.connectTCP(host, port, factory)

    reactor.run()

    elapsed = datetime.datetime.now() - start

    print 'Got %d poems in %s' % (len(addresses), elapsed)


if __name__ == '__main__':
    poetry_main()

最佳答案

我不认为我很确定你在问什么,但基本上如果你不需要对某个事件采取行动(例如当客户端开始连接或连接丢失时),你不需要' 需要实现该功能。它主要只是一个界面。如果您不实现这些函数,则会调用一个什么都不做的空函数,来自 ClientFactoryProtocol,或者您从中继承的任何类..

关于python - Twisted Python 接口(interface)实例是否可以不实现该接口(interface)的所有功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712187/

相关文章:

python - pytesser 成功率低?这是噪音问题,还是需要做其他事情?

python - ReportLab:大字体的文本挤在段落中

python - 在 AWS 上运行 Twisted 的问题

python - 编写优秀的 Twisted 网络资源

python - 按数字对字符串进行排序

php - 使用 php 下载 torrent 形式的 torcache.com。

python - spawnProcess 的简单示例

python - 使用Paramiko/Twisted模拟交互式SSH客户端

Python Gae 应用程序部署后不发送电子邮件

twisted - 如何限制 Twisted http 客户端的下载速率?