具有异步函数的装饰器

2024-05-31 07:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python实现一个实时网络摄像头服务,所以我希望使用aiortc。看看GitHub page上的例子,我发现了一个奇怪的东西,我不明白它是如何工作的

在examples文件夹的server/server.py上,有一个带有decorator的async函数。该函数从未被调用,因此我无法理解装饰器是如何工作的


    pc = RTCPeerConnection()
    
    .......

    @pc.on("iceconnectionstatechange")
    async def on_iceconnectionstatechange():
        log_info("ICE connection state is %s", pc.iceConnectionState)
        if pc.iceConnectionState == "failed":
            await pc.close()
            pcs.discard(pc)

在这种情况下,永远不会调用函数on_iceconnectionstatechange。以哪种方式调用@pc.on装饰器


Tags: 函数网络githubasyncserveronpage装饰
1条回答
网友
1楼 · 发布于 2024-05-31 07:28:09

RTCPeerConnectionAsyncIOEventEmitterlink)从^{} module继承pyee是一个事件系统模块。这个AsyncIOEventEmitter类是ondecorator方法的来源

从不直接调用on_iceconnectionstatechange函数,但装饰程序将其注册为事件侦听器,因此每当该事件被执行时,都会调用它,例如here

由于装饰器的工作方式,问题中的代码片段大致相当于:

decorator = pc.on("iceconnectionstatechange")

async def on_iceconnectionstatechange():
    log_info("ICE connection state is %s", pc.iceConnectionState)
    if pc.iceConnectionState == "failed":
        await pc.close()
        pcs.discard(pc)

on_iceconnectionstatechange = decorator(on_iceconnectionstatechange)

以下是decorator(来自here)的“定义”片段:

def _on(f):
    self._add_event_handler(event, f, f)
    return f

这里,event的值是"iceconnectionstatechange",因此代码相当于:

async def on_iceconnectionstatechange():
    log_info("ICE connection state is %s", pc.iceConnectionState)
    if pc.iceConnectionState == "failed":
        await pc.close()
        pcs.discard(pc)

pc._add_event_handler("iceconnectionstatechange", on_iceconnectionstatechange, on_iceconnectionstatechange)

因为调用了decorator函数,所以它可以在一些内部字典中注册on_iceconnectionstatechange,以便在发出相关事件时调用它。decorator注册事件侦听器而不直接调用on_iceconnectionstatechange,因为它在创建时注册,而不是等待调用

相关问题 更多 >