Python 使用 class 时未调用回调

Python callback not called when using class

所以这是我的代码:

import asyncio
import logging
from asyncio import AbstractEventLoop

from aio_pika import connect, IncomingMessage


def test_one(a, b):
    print("test_one", a, b)


class Consumer:
    def __init__(self, url):
        self.url = url

    async def run(self, loop: AbstractEventLoop):
        while True:
            try:
                connection = await connect(self.url, loop=loop)
                connection.add_close_callback(test_one)
                connection.add_close_callback(self.test_two)

                # Creating a channel
                channel = await connection.channel()

                # Declaring queue
                queue = await channel.declare_queue("snapshots")

                logging.info("Started listening")

                # Start listening the queue with name 'hello'
                await queue.consume(self.on_message, no_ack=True)
                break
            except:
                logging.error("Could not connect")
            finally:
                await asyncio.sleep(1)

    def on_message(self, message: IncomingMessage):
        print(message.body)

    def test_two(self, a, b):
        print("closed", a, b)

我的问题是当我断开连接时它只调用 test_one 函数,但它不调用 class 中的 test_two 函数。我不明白。我尝试只添加 test_two 函数,但那也不起作用。尝试删除参数。同样的问题。我没主意了。你知道我做错了什么吗?

顺便说一下,self.on_message 确实有效。

可能 API 正在创建对传递给它的回调函数的弱引用。尝试在传递之前创建对回调函数的强引用。

self._cb_func = self.test_two
connection.add_close_callback(self._cb_func)

完整代码:

import asyncio
import logging
from asyncio import AbstractEventLoop

from aio_pika import connect, IncomingMessage


def test_one(a, b):
    print("test_one", a, b)


class Consumer:
    def __init__(self, url):
        self.url = url

    async def run(self, loop: AbstractEventLoop):
        while True:
            try:
                connection = await connect(self.url, loop=loop)
                connection.add_close_callback(test_one)
                self._cb_func = self.test_two
                connection.add_close_callback(self._cb_func)

                # Creating a channel
                channel = await connection.channel()

                # Declaring queue
                queue = await channel.declare_queue("snapshots")

                logging.info("Started listening")

                # Start listening the queue with name 'hello'
                await queue.consume(self.on_message, no_ack=True)
                break
            except:
                logging.error("Could not connect")
            finally:
                await asyncio.sleep(1)

    def on_message(self, message: IncomingMessage):
        print(message.body)

    def test_two(self, a, b):
        print("closed", a, b)

如果你有很多回调函数,那么这个问题中有将它们存储为数组的答案:using python WeakSet to enable a callback functionality