我们如何json.dumps
在构造函数中直接使用,而不是通过单独的函数调用它?
def json_serialize(obj, *args):
return json.dumps(obj)
class KafkaProducer(object):
def __init__(self, config):
config = {
"key.serializer": json_serialize,
"value.serializer": json_serialize,
}
self.producer = SerializingProducer(config)
def produce(self, *args, **kwargs):
self.producer.produce(*args, **kwargs)
self.producer.flush()
当我使用 KafkaProducer 类的生产方法时,它适用于上述实现。由于 json_serialize 函数仅用于json.dumps(obj)
.
json.dumps
如果我使用如下所示的直接输入尝试此操作KafkaProducer
,然后调用产生类方法,它将不起作用。给出错误为:
KafkaError{code=_KEY_SERIALIZATION,val=-162,str="dumps() takes 1 positional argument but 2 were given"}
class KafkaProducer(object):
def __init__(self, config):
config = {
"key.serializer": json.dumps,
"value.serializer": json.dumps,
}
self.producer = SerializingProducer(config)
def produce(self, *args, **kwargs):
self.producer.produce(*args, **kwargs)
self.producer.flush()