簡體   English   中英

使用 python 在文件中寫入 avro 記錄

[英]Write avro record in file using python

我有一個名為 test.avsc 的 avro 文件,其架構為:

{
    "namespace": "test",
    "type": "record",
    "name": "test.schema",
    "fields": [
      { "name": "device", "type": ["null", "string"] , "default" : null }
    ]
}

我的 avro class 是:

import avro.schema
from avro.datafile import DataFileWriter
from avro.io import DatumWriter

class AvroHelper(object):

    avro_writer = None
    codec = 'deflate'

    def __init__(self, schemaf, avrofile):
        schema = avro.schema.parse(schemaf)
        self.avro_writer = DataFileWriter(avrofile, DatumWriter(), schema, codec=self.codec)
        self.num_rows_written_to_avro = 0

    def append(self, row):
        self.avro_writer.append(row)

我正在嘗試將數據寫入:

file = open('test1.avro', 'wb')
avro_writer = AvroHelper('test.avsc', file)

rec= { 'device': "1" }
avro_writer.append(rec)

我在嘗試將 avro 記錄寫入文件時遇到異常:


File "search_console_api_client.py", line 31, in __init__
    schema = avro.schema.parse(schema_str)
  File "/usr/local/lib/python3.7/site-packages/avro/schema.py", line 1238, in parse
    % (json_string, exn))
avro.schema.SchemaParseException: Error parsing schema from JSON: 'test.avsc'. Error message: JSONDecodeError('Expecting value: line 1 column 1 (char 0)').

我怎樣才能讓它工作?

你在做

avro_writer = AvroHelper('test.avsc', file)

這意味着您的__init__正在發生這種情況:

schema = avro.schema.parse('test.avsc')

但是, parse() function 應該接受架構的 JSON 字符串,而不是文件名。 相反,您可能想做這樣的事情:

avro_writer = AvroHelper(open('test.avsc').read(), file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM