Skip to content

pydantic_modelsの追加 #698

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 22, 2025
Merged

pydantic_modelsの追加 #698

merged 8 commits into from
Jan 22, 2025

Conversation

yuji38kwmt
Copy link
Collaborator

@yuji38kwmt yuji38kwmt commented Jan 21, 2025

OpenAPI Generator v7を用いてpydantic_modelsを作成しました。

背景

もともと主要なスキーマのみdataclassを自動生成していました。
自動生成ではカスタムテンプレート(models.mustache)を用意して、catでファイルを連結したり複雑なことをしていました。

メンテナンスをもう少し楽にするため、OpenAPI Generatorが生成したmodelsを採用することにしました。
OpenAPI Generator v4のときと比較すると、v7が生成したmodelsは利用しやすいです。
たとえばPydanticが使われています。

したがって、OpenAPI Generatorが生成したmodelsをそのまま利用することにしました。

考えたこと

既存のmodels.pyは残すため、pydantic_models/というディレクトリに配置しました。

今後の運用

実際に使ってみて利用できそうなら、annofabapi/models.py, annofabapi/dataclass/*.pyを非推奨にする。

Comment on lines +101 to +115
replace_from_dict_method() {
# `from_json`メソッドで`_type`が正しくない場合は`ValueError`を発生させるようにする
# 本来は`from_dict`メソッドを修正すべきだが、
local type_value=$1
local filename=$2
sed "s/return cls\.from_dict(json\.loads(json_str))/result = cls.from_dict(json.loads(json_str))\\n if result.type != \"$type_value\": raise ValueError(\"Invalid type\")\\n return result/" out/openapi_client/models/${filename} --in-place
}
# `from_dict`メソッドで`oneOf`に該当するスキーマが複数見つかる場合はErrorが発生する
# その場合は、`type`の値を判定するようにした
replace_from_dict_method Movie system_metadata_movie.py
replace_from_dict_method Image system_metadata_image.py
replace_from_dict_method Custom system_metadata_custom.py
replace_from_dict_method Classification full_annotation_data_classification.py
replace_from_dict_method Segmentation full_annotation_data_segmentation.py
replace_from_dict_method SegmentationV2 full_annotation_data_segmentation_v2.py
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parseできない場合のみ、_typeの値を判定するようにした。

@yuji38kwmt yuji38kwmt merged commit bc6d2fa into main Jan 22, 2025
8 checks passed
@yuji38kwmt yuji38kwmt deleted the add-pydantic branch January 22, 2025 03:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant