【问题标题】:How to validate a Host field in python pydantic?如何验证 python pydantic 中的主机字段?
【发布时间】:2021-11-18 18:30:15
【问题描述】:

当您有要验证的主机字段时,主机可以是:

ipv4地址:127.0.0.1

ipv6地址:2001:db8:ff00:42

example.com

int.domain: puny£code.com

11.11.101.11.example.org

任何建议,如何使用 pydantic 验证字段?

【问题讨论】:

  • 我不知道 pydantic,但是这些值类型中的任何一个都可以通过某种解析和验证来描述,因此整个“主机字段”是这些类型的聚合。如果其中任何一个解析成功,则该字段条目是有效的。
  • 如果您付出一些研究努力,您将更有可能获得帮助。

标签: python hostname pydantic


【解决方案1】:

我会查找一些正则表达式并使用 constr(regex=...) 或使用来自 https://pydantic-docs.helpmanual.io/usage/types/https://pydantic-docs.helpmanual.io/usage/types/#urls 的一些预制类型

https://pydantic-docs.helpmanual.io/usage/types/#arguments-to-constr

然后使用


from typing import Union
from ipaddress import IPv4Address
from pydantic import BaseModel, HttpUrl, parse_obj_as


class X(BaseModel):
    host: Union[HttpUrl,IPv4Address,...]

parsed_host = parse_obj_as(X, your_host)

【讨论】:

  • 你能描述更多关于正则表达式应该包含的内容吗?......只是“使用正则表达式”并且指向文档的链接 constr 并不是特别有用! .. pydantic 实际上提供了 IP 验证和一些 URL 验证,可以在一些 Union 中使用,也许还可以使用正则表达式
  • 你有代码吗?
  • @ti7 更新了一点,合适吗?
  • @Leemosh 但是当你有一个像 11.11.101.11.example.org 这样的主机时它不会解决
  • 然后按照我之前的建议在 constr 中使用正则表达式。经过几秒钟的谷歌搜索后,我找到了reg = "^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$" constr(regex=reg),它适用于那个奇怪的主机。
猜你喜欢
  • 2023-02-09
  • 2021-10-05
  • 2020-10-24
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多