Created
May 18, 2016 18:04
-
-
Save r39132/f94484efa68a8ca4d2d23a4260436c7a to your computer and use it in GitHub Desktop.
Writing Avro Without A Schema in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import avro.schema | |
import io, random | |
from avro.io import DatumWriter, DatumReader | |
import avro.io | |
# Path to user.avsc avro schema | |
schema_path="user.avsc" | |
schema = avro.schema.parse(open(schema_path).read()) | |
for i in xrange(1): | |
writer = avro.io.DatumWriter(schema) | |
bytes_writer = io.BytesIO() | |
encoder = avro.io.BinaryEncoder(bytes_writer) | |
writer.write({"name": "123", "favorite_color": "111", "favorite_number": random.randint(0,10)}, encoder) | |
raw_bytes = bytes_writer.getvalue() | |
print(raw_bytes) | |
bytes_reader = io.BytesIO(raw_bytes) | |
decoder = avro.io.BinaryDecoder(bytes_reader) | |
reader = avro.io.DatumReader(schema) | |
user1 = reader.read(decoder) | |
print(" USER = {}".format(user1)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"namespace": "example.avro", | |
"type": "record", | |
"name": "User", | |
"fields": [ | |
{"name": "name", "type": "string"}, | |
{"name": "favorite_number", "type": ["int", "null"]}, | |
{"name": "favorite_color", "type": ["string", "null"]} | |
] | |
} |
I think that line 8 with latests versions of Avro should be written as:
schema = avro.schema.Parse(open(schema_path).read())
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output is