【问题标题】:How can I create a server Protocol class with an __init__ function?如何使用 __init__ 函数创建服务器协议类?
【发布时间】:2015-09-13 10:59:14
【问题描述】:

我来自 Twisted 背景,因此我对 Twisted 实现的协议和工厂有深入的了解。但是,我正在切换到 asyncio,我在理解工厂如何集成到这个特定框架中时遇到了一些麻烦。

official documentation 中,我们有一个服务器的asyncio.Protocol 类定义示例。它没有用户自定义的__init__函数,所以我们可以简单地调用loop.create_server(EchoServerClientProtocol, addr, port)

如果我们的Protocol 需要实现一些初始化逻辑会发生什么?例如,考虑这个设置最大缓冲区大小的示例:

import asyncio
from collections import deque

class BufferedProtocolExample(asyncio.Protocol):
    def __init__(self, buffsize=None):
        self.queue = deque((), buffsize)

    # ...

在 Twisted 中,您将创建一个 Factory 类来保存所有配置值,然后将其传递给初始化连接的函数。 Asyncio seems to work in the same way,但我找不到任何文档。

可以使用functools.partial,但是处理这种情况的正确方法是什么?

【问题讨论】:

标签: python python-asyncio


【解决方案1】:

文档has an example where they use a lambda for this,所以我猜 functools.partial 没问题。他们还state that protocol_factory can be any callable。所以要拥有像 Twisted 的工厂这样的东西,你只需要在一个类上实现 __call__,就像在 Twisted 中实现 buildProtocol 一样。

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多