【问题标题】:How to specify python faust.Record field which name starts with numbers?如何指定名称以数字开头的python faust.Record字段?
【发布时间】:2021-04-25 00:16:12
【问题描述】:

我通过扩展 faust.Record 类来描述浮士德模型。我的输入 json 看起来像:

{
  "1": "some_string"
  "2": "some_string"
}

所以我必须创建类字段,只用数字命名。我知道,它通常在 Python 中受到限制,但是有什么解决方法,比如我的 fieds 名称的别名?

我正在寻找类似 Java 中的 Jackson 注释:

import faust

class Model(faust.Record, serializer='json'):
    @alias(field_name: '1')
    first_name: str
    @alias(field_name: '2')
    last_name: str

【问题讨论】:

  • 是否有特定的理由使用模型类而不是让数据成为字典?

标签: python json faust


【解决方案1】:

如果没有适当的数据模型,没有简单的方法可以神奇地挽救一个主题。

你不应该在没有数据模型的情况下写一个 kafka 主题。

正如@OneCricketeer 建议的那样,您应该将未定义的主题提取为字典。

之后,您可以编写一个使用该主题的代理,将您的模型转换为适当的数据模型并将其写入主题。

class Person(faust.Record):
    first_name: str
    last_name: str

现在您可以开始使用您的例如符合预期的人模型。

undeclared_json_topic = app.topic('name_of_your_input_topic')
person_topic = app.topic('person', value_type=Person)

@app.agent(undeclared_json_topic)
async def migrate_to_person(json_stream: faust.Stream) -> faust.Stream[Person]:
    async for json in json_stream:
        person = Person(first_name=json['1'], last_name=json['2'])
        await person_topic.send(value=person)
        yield

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多