官網示例文檔:http://avro.apache.org/docs/current/gettingstartedpython.html#download_installhtml
須要注意的是,官網給出的是py2.x的示例代碼。python
py3 須要作一些改動:apache
import avro.schema from avro.datafile import DataFileReader, DataFileWriter from avro.io import DatumReader, DatumWriter schema = avro.schema.Parse(open("user.avsc", "rb").read()) writer = DataFileWriter(open("users.avro", "wb"), DatumWriter(), schema) writer.append({"name": "Alyssa", "favorite_number": 256}) writer.append({"name": "Ben", "favorite_number": 7, "favorite_color": "red"}) writer.close() reader = DataFileReader(open("users.avro", "rb"), DatumReader()) for user in reader: print(user) reader.close()
user.avsc 文件哪來?
直接將文章中的如下內容存到文件中就好了。
{"namespace": "example.avro", "type": "record", "name": "User", "fields": [ {"name": "name", "type": "string"}, {"name": "favorite_number", "type": ["int", "null"]}, {"name": "favorite_color", "type": ["string", "null"]} ] }