1

我正在寻找一些关于在 Python 中实现一组仅数据值的“接口”的最佳方法的建议,这些接口相当于它们的打字稿对应物(我们有一个项目,我们同时使用两者,并希望强制执行一致他们的通信接口,这将通过将 python 序列化为 json 以拉入 TS 组件)

接口将是组合,以保持模块化和简单。

给定一组 TS 接口定义为:

interface TestOutput {
  phantom: string
  testDateTime: datetime
  author: string
  result: boolean
  report_summaryFile?: string // the '?' means this field is optional
  // ... more values
  series: Array<Series>
  soloImages: Array<Images>
}

interface Series {
  number: number
  filter: string
  kernel: string
  // ... more values
  images: Array<TestImage>
}

我正在考虑使用数据类并执行以下操作:

from dataclasses import dataclass
from typing import List
import datetime

@dataclass
class TestSeries:
    seriesNum: int 
    modality: str 
    description: str = ''

@dataclass
class TestOutput:
    phantom: str 
    testDateTime: datetime.datetime
    author: str 
    result: bool
    series: List[TestSeries]
    soloImages: List[Images]
    report_summaryFile: str = ''

数据类是最好的方法吗?

4

1 回答 1

2

pydantic 是一个很好的库。
我做了类似的事情,但仅适用于数据类 - ValidatedDC:

from dataclasses import dataclass
from typing import List

from validated_dc import ValidatedDC
import json


@dataclass
class Series(ValidatedDC):
    series_num: int
    modality: str
    description: str = ''


@dataclass
class Output(ValidatedDC):
    phantom: str
    date_time: str
    author: str
    result: bool
    series: List[Series]
    report_summary_file: str = ''


# For example, by API we got a JSON string:
input_json_string = '''
    {
        "phantom": "test_phantom",
        "date_time": "2020.01.01",
        "author": "Peter",
        "result": true,
        "series": [{
            "series_num": 1,
            "modality": "test_modality"
        }]
    }
'''

# Load the string into the dictionary:
input_data = json.loads(input_json_string)

# Then create a dataclass to check the types of values and for the
# convenience of further work with data:
output = Output(**input_data)

# Since valid data were obtained, there are no errors
assert output.get_errors() is None

# Let's say we got data with an error:
input_data['series'][0]['series_num'] = '1'  # The string is not an integer!

output = Output(**input_data)
assert output.get_errors()
print(output.get_errors())
# {
#    'series': [
#        InstanceValidationError(
#            value_repr="{'series_num': '1', 'modal...}",
#            value_type=<class 'dict'>,
#            annotation=<class '__main__.Series'>, exception=None,
#            errors={
#                'series_num': [
#                    BasicValidationError(
#                        value_repr='1', value_type=<class 'str'>,
#                        annotation=<class 'int'>, exception=None
#                    )
#                ]
#            }
#        ),
#        ListValidationError(
#            item_index=0, item_repr="{'series_num': '1', 'modal...}",
#            item_type=<class 'dict'>, annotation=<class '__main__.Series'>
#        )
#    ]
# }

有关更多详细信息,请参见此处:
https ://github.com/EvgeniyBurdin/validated_dc

于 2020-05-16T07:20:00.120 回答