如何在Python中提取Avro文件的模式

21
我正在尝试使用Python Avro库(https://pypi.python.org/pypi/avro)读取由JAVA生成的AVRO文件。由于模式已经嵌入在avro文件中,为什么还需要指定模式文件?是否有自动提取它的方法?
发现另一个名为fastavro(https://pypi.python.org/pypi/fastavro)的软件包可以提取avro模式。在Python arvo软件包中手动指定模式文件是设计上的吗?非常感谢。
3个回答

14

我使用 Python 3.4 和 Avro 包 1.7.7。

用于模式文件,请使用:

reader = avro.datafile.DataFileReader(open('file_name.avro',"rb"),avro.io.DatumReader())
schema = reader.meta
print(schema) 

这在Python 2.7中也很好用。我的导入语句如下(不确定您需要多少): import avro.schema from avro.datafile import DataFileReader from avro.io import DatumReader - B. Griffiths

10

直接检查/usr/local/lib/python2.7/site-packages/avro/datafile.py文件可以找到答案:

reader = avro.datafile.DataFileReader(input,avro.io.DatumReader())
schema = reader.datum_reader.writers_schema
print schema

有趣的是,在Java中有一个专门的方法可以实现这个功能:reader.getSchema()


2

在我的情况下,为了获得模式作为一个“可消耗”的Python字典,包含有用的信息,如模式名称等,我执行了以下操作:

reader: DataFileReader = DataFileReader(open(avro_file, 'rb'), DatumReader())
schema: dict = json.loads(reader.meta.get('avro.schema').decode('utf-8'))

reader.meta 是一个字典,但是它本身并没有什么用处。它只包含两个键:avro.codecavro.schema,它们都是 bytes 对象(所以我必须解析它才能访问属性)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接