【发布时间】: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,但是处理这种情况的正确方法是什么?
【问题讨论】:
-
文档has an example where they use a lambda for this,所以我猜
functools.partial没问题。他们还state thatprotocol_factorycan be any callable。 -
@Phillip 非常感谢。请随时重申这一点作为答案,我很乐意接受。
-
create_connection 和 create_server 最终都运行
protocol = protocol_factory()(参见代码 here 和 there)。
标签: python python-asyncio