我正在使用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))
虽然这有效,但我在函数完成错误后收到:
类型错误:"NoneType"对象不可调用 149号线,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()
(,而你的回调函数返回 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)