How to read Avro files from S3 in Python?

Viewed 4610

I have a bunch of Avro files that I would like to read one by one from S3. I have no problem reading the files as bytes but I am wondering how can you iterate over the entires after that. Current code:

conn = boto.s3.connect_to_region("us-east-1")
my_bucket=boto.s3.bucket.Bucket(conn, "my_bucket")
my_key = my_bucket.get_key("folder/file.avro")
raw_bytes = my_key.read()

test_schema = '''
{
  "namespace": "com.company",
  "type": "record",
  "name": "MimeMessage_v2",
  "fields": [
    {
      "name": "record_timestamp",
      "type": "long"
    },
    {
      "name": "contents",
      "type": "bytes"
    }
  ],
  "message_id": 2
}
'''
schema = avro.schema.Parse(test_schema)
#this is the problematic section
dreader = DatumReader(schema, schema)
v = dreader.read(raw_bytes)

I am wondering how to read a variable containing bytes of a Avro file properly.

1 Answers

Here is one of the ways that worked for me in Python 3:

from avro.datafile import DataFileReader
avro_bytes = io.BytesIO(raw_bytes)
reader = DataFileReader(avro_bytes, avro.io.DatumReader())
for line in reader:
    print(line)
Related