Kombu - 消息发布到rabbitmq错误 - TypeError:'str'对象不可调用

时间:2013-08-20 16:40:47

标签: python rabbitmq amqp kombu

我想首先说我不仅仅是python,而是一般的编程。考虑到这一点,这是我的问题。我正在尝试将一些数据发送到我的Rabbitmq服务器。下面是我的Python代码。 json_data只是一个包含一些json格式数据的变量。

with Connection("amqp://username:password@test_server.local:5672/#/") as conn:
    channel = conn.channel()
    producer = Producer(channel, exchange = "test_exchange", serializer="json")

    producer.publish(json_data)

print "Message sent"

这会产生以下错误:

Traceback (most recent call last):   File "test.py", line 43, in <module>     producer = Producer(channel, exchange = "test_exchange", serializer="json")   File "/Library/Python/2.7/site-packages/kombu/messaging.py", line 83, in __init__     self.revive(self._channel)   File "/Library/Python/2.7/site-packages/kombu/messaging.py", line 210, in revive     self.exchange = self.exchange(channel) TypeError: 'str' object is not callable

任何帮助将不胜感激。感谢。

2 个答案:

答案 0 :(得分:1)

在我的头撞到我的桌子后,我发现Python不喜欢交换的召唤。然后我的同事告诉我,如果我在出版商中包含交换和路由密钥,它可能会更好。所以现在我的新代码看起来像这样。

# Creates the exchange and queue and binds them
# If already created on the server side these steps are not needed
exchange = Exchange("test_exchange", "direct", durable=True)
queue = Queue("test_q", exchange = exchange, routing_key = "test")

# The last foreword slash is the virtual host
with Connection("amqp://username:password@hostname:5672/", "/") as conn:
    channel = conn.channel()
    producer = Producer(channel, exchange = exchange, serializer="json")

    for key, value in json_data.items():
        producer.publish(exchange = exchange, routing_key = "test", body = {key:value})

print "Message sent!"

答案 1 :(得分:0)

我正在回答这个问题 - 因为你的答案并没有确定真正的问题,即TypeError: 'str' object is not callable at self.exchange = self.exchange(channel) - 表明你正在将错误的类型传递给exchange param即通过&#39; str&#39;到exchange

producer = Producer(channel, exchange = "test_exchange", serializer="json")

解决方案:您将价值传递给&#39; 交换&#39; param必须是Exchange对象。

您的代码必须是:

with Connection("amqp://username:password@test_server.local:5672/#/") as conn:
    channel = conn.channel()
    exchange = Exchange(name='inbound') # the minimal declaration
    producer = Producer(channel, exchange=exchange, serializer="json")

    producer.publish(json_data)

print "Message sent"

有关Exchange参数的完整列表 - docs

我在队列声明中遇到了同样的错误,即

queue = Queue(name=queue_name, exchange='host_tasks', routing_key=binding_key)
bound_queue = queue(channel) # only once bound, we can call declare(), purge(), delete() on exchange

所以宣布交换,例如

exchange = Exchange('host_tasks', 'direct', durable=True)
queue = Queue(name=queue_name, exchange=exchange, routing_key=binding_key)
bound_queue = queue(channel)

不要忘记导入Exchange