如何向 pubsub 回调添加参数

How to add an argument to pubsub callback

我正在使用 pubsub 库向特定主题发布消息:

# init publisher
publisher = pubsub_v1.PublisherClient(credentials=credentials)

# publish iteratively and keep track of the original iter id
for iter in [0,1,2,3,4]:
   message_future = self.publisher.publish(topic_path)
   message_future.add_done_callback(callback)

# callback
def callback(message_future):
   print(message_future)
   # how can I capture here the original "iter"?

不过,我想添加一些元数据,例如:

message_future.add_done_callback(callback(message_future, iter=iter))

虽然这有效,但我在函数完成后收到错误:

TypeError: 'NoneType' object is not callable line 149, in add_done_callback

发生了什么事?

另请参阅: https://googleapis.dev/python/pubsub/latest/publisher/index.html

您需要在 add_done_callback 中传递一个函数。

def foo():
    print('hello')

message_future.add_done_callback(foo)

在add_done_callback里面,函数是这样执行的

def add_done_callback(self, func):
    ...
    func(self)

问题是您在传递回调函数之前对其求值 (message_future.add_done_callback(foo()),并且您的回调函数 returns None。所以消息试图执行 None 对象,因此出现错误。

您可以创建一个 Callable class 来将所有元数据存储为 class 成员,然后在回调函数中使用它。

class Callable:
  def __init__(self, idx):
    self.idx = idx

  def callback(self, message_future):
    print(message_future)
    print(self.idx)

# publish iteratively and keep track of the original iter id
for iter in [0,1,2,3,4]:
  callable = Callable(iter)
  message_future = self.publisher.publish(topic_path)
  message_future.add_done_callback(callable.callback)