Python 如何出版卡夫卡词典?
我正试图在卡夫卡主题中发表回应。此响应是从mongodb获取的Python 如何出版卡夫卡词典?,python,python-3.x,apache-kafka,Python,Python 3.x,Apache Kafka,我正试图在卡夫卡主题中发表回应。此响应是从mongodb获取的 from kafka import KafkaProducer from kafka.errors import KafkaError import json import pymongo from pymongo import MongoClient import sys import datetime try: client = MongoClient('mongodb://A.B.C.D:27017/prod-pro
from kafka import KafkaProducer
from kafka.errors import KafkaError
import json
import pymongo
from pymongo import MongoClient
import sys
import datetime
try:
client = MongoClient('mongodb://A.B.C.D:27017/prod-production')
db = client["prod-production"]
except Exception as e:
print("Error occurred while connecting to DB")
print(e)
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
producer = KafkaProducer(retries=5)
print("Initial time:")
print(datetime.datetime.now())
count = 1
for response in db.Response.find():
if count >= 20:
producer.flush()
sys.exit()
count += 1
print(count)
producer.send('example-topic', bytes(response))
print("Final time")
print(datetime.datetime.now())
我得到以下错误:
Traceback (most recent call last): File "producer.py", line 28, in <module>
producer.send('collect-production-response', bytes(response)) TypeError: 'str' object cannot be interpreted as an integer
Traceback(最近一次调用last):文件“producer.py”,第28行,在
producer.send('collect-production-response',bytes(response))TypeError:'str'对象不能解释为整数
但是,在python2中,这个错误不会发生。我遇到了这个问题,我用以下两种方法解决了它
1- producer.send('example-topic', bytes(str(response), 'utf-8'))
或
1) 使用
json.dumps
而不是bytes
2)我可能建议查看Debezium或Kafka Connect项目,以便让Mongo进入KafkaPython 2中。2将“str”和“bytes”视为同一事物,但将“unicode”视为不同的对象。Python3将“str”和“unicode”视为同一事物,但将“bytes”视为不同的对象。@cricket_007请发布一个答案,作为您的评论,从现在开始,以便我接受它。
2- producer.send('example-topic', str(response))