当模型字段是另一个模型时Faust反序列化模型

问题描述 投票:0回答:1

我有一个有点复杂的模型,其中一个字段可以是其他几个模型之一,看起来类似于以下内容:

'''These are the options'''
class ChatterFilter(Record, serializer='json'):
  counts:int
  time:int
  init_state:str
  new_state:str
  stale_time:int
  comment:str


class LimitFilter(Record, serializer='json'):
  lolo:float
  low:float
  high:float
  hihi:float
  comment:str


class DitherFilter(Record, serializer='json'):
  stale_time:int
  init_state:str
  new_state:str
  comment:str

class FitlerOptions(FieldDescriptor[type]):
  ''' This class defines the allowable filter types and validates these on initialisation '''
  def __init__(self, choices: List[type], **kwargs: Any) -> None:
    self.choices = choices
    super().__init__(choices=choices, **kwargs)

  def validate(self, value: type) -> Iterable[ValidationError]:
    if type(value) not in self.choices:
      yield self.validation_error(
        f'{self.field} must be one of {self.choices}, received:\t{value}=>{type(value)}')

class Filter(Record, serializer='json', validation=True):
  filter: type = FitlerOptions([ChatterFilter, LimitFilter, DitherFilter, type(None)])
  initiated:str=None
  end:str=None
  duration:float=None
  initiator:str=None

我们的想法是确保过滤器是 3 种类型之一(如果没有过滤器则为 None),因此我们使用此方法创建一个模型来验证提供的类型。

这似乎工作得很好......直到我们尝试将它发送到一个主题,然后读取传入的事件,它无法从序列化字典中反序列化过滤器,并抱怨它是一个字典,而不是允许的选项之一错误日志是

received:    {'counts': 0, 'time': 0, 'init_state': 'NO_ALARM', 'new_state': 'LOLO', 'stale_time': 60, 'comment': 'comment string', '__faust': {'ns': 'models.models.ChatterFilter'}}=><class 'dict'>

很明显,这是一个模型,faust 应该能够识别它,但默认情况下它似乎并没有这样做。我可以在验证中添加检查,并在尝试不成功时生成转换后的版本和错误,但似乎我不必这样做。

python faust
1个回答
0
投票

所以它确实有效。只需进行不同的设置即可将其指定为列表:

类过滤器(记录): mask:List[Union[ChatterFilter, LimitFilter, DitherFilter]]=[]

现在可以按预期工作了。

© www.soinside.com 2019 - 2024. All rights reserved.