1
0

【FastAPI】PydanticでIPv4Addressのインポートエラーが出る理由とは?

Last updated at Posted at 2023-07-29

概要

FastAPIでpydanticを使ったコードを実行したら、以下のエラーが出た。
IPv4Addressとはなんぞや?pydanticと関係あるの?と思ったので調べてみました。

    from pydantic import BaseModel
  File "pydantic/__init__.py", line 2, in init pydantic.__init__
  File "pydantic/dataclasses.py", line 43, in init pydantic.dataclasses
    # | <blank> | No action: no method is added.          |
  File "pydantic/error_wrappers.py", line 4, in init pydantic.error_wrappers
  File "pydantic/json.py", line 5, in init pydantic.json
ImportError: cannot import name IPv4Address

ImportErrorの原因

このエラーは、ImportErrorの通り、pydanticモジュールにおいてIPv4Addressのインポートが失敗していることに起因しています。

通常、IPv4Addressクラスは Python の標準モジュールである ipaddressモジュールに含まれています。しかし、pydanticモジュールが内部でipaddressを使う場合、Pythonの環境によってはipaddressモジュールが見つからない場合があるよう。(Python 3.3以上のバージョンを使用している場合は、通常ipaddressモジュールが標準で含まれているようです)

以下でインストールできます。

pip install ipaddress

IPv4Addresspydanticの関係とは?

IPv4Addressは、IPv4(Internet Protocol version 4)アドレスを表すためのクラス。
このクラスを使用すると、IPv4アドレスのパース、検証、ネットワークアドレスの取得などが容易に行えます。

公式ドキュメント:ipaddress --- IPv4/IPv6 操作ライブラリ

class ipaddress.IPv4Address(address)
IPv4 アドレスを構築する。 address が正しい IPv4 アドレスでない場合、 AddressValueError を発生させます。

なぜこれがpydanticと関係あるの?と思ったら、pydanticは、データのバリデーションに際して、データ型やフォーマットの指定ができる柔軟性を持っていて、IPv4アドレスなどの特定のデータ型をバリデーションする際にも利用されることがあるからですね。x

ということでpydanticIPv4Addressを含む様々なデータ型をサポートし、データのバリデーションを行える汎用的なデータ処理ライブラリ、ゆえに上述のインポートエラーが表示されたというわけです。

以前、pydanticBaseModelクラスを解説する記事を書いたのでご参考までに。
【FastAPI】Pydanticを使ってバリデーション:none is not an allowed valueエラーの解決方法

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0