在消息包含多个消息时编译avro模式(python)

3 投票
1 回答
1588 浏览
提问于 2025-04-17 11:59

我在Python中使用import avro等来编译avro模式。有时候,我的avro模式看起来像这样:

{ name: "Message1" ..... }

{ name: "Message2", "fields": [ { "type": "Message1", "name": "previous_avro_schema" } ] } ...

请忽略拼写错误。我只是想传达我的意思。重点是我有两个avro模式。其中一个avro模式把第二个avro模式当作它的一个字段。对于这样的avro消息,我该如何调用avro.schema.parse(....),才能让它们正确编译呢?

1 个回答

0

Avro在Python中的支持实在是太差了,不过你还是可以让一些东西正常工作,包括同时使用多个模式(schema)。你只需要把这些模式文件合并成一个文件,而且要确保它们的合并顺序是正确的,也就是说,依赖的部分要放在前面。还需要把名字替换成实际的模式。下面是我用来合并它们的脚本:

def resolve(path):
    "fully resolve a schema that includes other schemas"
    data = open(path).read()
    # fill in any while they remain
    while True:
        beg = data.find('`')
        end = data.find('`', beg + 1)
        if beg < 0:
            break
        path = os.path.join(os.path.dirname(path), data[beg+1:end] + '.avsc')
        data = data[:beg] + resolve(path) + data[end+1:]
    return data

撰写回答