【问题标题】:Write avro record in file using python使用python在文件中写入avro记录
【发布时间】:2021-03-16 12:19:28
【问题描述】:

我有一个名为 test.avsc 的 avro 文件,其架构为:

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

我的 avro 课程是:

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)').

我怎样才能让它工作?

【问题讨论】:

  • 错误说文件test.avsc不是一个有效的JSON文件,而Expecting value: line 1 column 1 (char 0)让我们认为文件是空的。您是否因为没有使用完整路径而读取了错误的文件?
  • @SergeBallesta 也尝试过使用完整路径。而且文件不是空的。
  • 我只翻译了 Python 错误所说的内容...为确保,以文本形式打开文件并打印其内容。

标签: python python-3.x avro


【解决方案1】:

你在做

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

这意味着您的__init__ 正在发生这种情况:

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

但是,parse() 函数应该接受模式的 JSON 字符串,而不是文件名。相反,您可能想做这样的事情:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2020-10-16
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多