0

我正在使用 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”对象在 add_done_callback 中的第 149 行不可调用

怎么了?

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

4

1 回答 1

2

您应该在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()),并且您的回调函数返回 None。因此消息正在尝试执行 None 对象,因此出现错误。

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

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)
于 2019-11-27T18:14:56.927 回答