这个
PhoneNumber
类具有以下类变量:
#https://github.com/pydantic/pydantic-extra-types/blob/092251d226edcf4e06bbe4f904da177fad20a6de/pydantic_extra_types/phone_numbers.py#L26
default_region_code: str | None = None
phone_format: str = 'RFC3966'
min_length: int = 7
max_length: int = 64
如果我们遵循一堆代码链,我们最终会陷入
phonenumber
存储库
电话号码
取决于。这是数据返回之前的最后一站
电话号码
,我们可以看到
phone_format
最终会通过以下方式影响电话号码:
#https://github.com/daviddrysdale/python-phonenumbers/blob/2f06ef6db2ca83f3856fbb8019a0c665f5971b13/python/phonenumbers/phonenumberutil.py#L1726
def _prefix_number_with_country_calling_code(country_code, num_format, formatted_number):
"""A helper function that is used by format_number and format_by_pattern."""
if num_format == PhoneNumberFormat.E164:
return _PLUS_SIGN + unicod(country_code) + formatted_number
elif num_format == PhoneNumberFormat.INTERNATIONAL:
return _PLUS_SIGN + unicod(country_code) + U_SPACE + formatted_number
elif num_format == PhoneNumberFormat.RFC3966:
#_RF3966_PREFIX = 'tel:'
return _RFC3966_PREFIX + _PLUS_SIGN + unicod(country_code) + U_DASH + formatted_number
else:
return formatted_number
值得注意的是,如果您使用无法识别的格式,则上述内容仅返回格式化的数字。奇怪的是,在上述条件中没有“国家”格式。使用它应该会触发
else
.
这应该能解决你的问题。
from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumber
PhoneNumber.phone_format = 'E164' #'INTERNATIONAL', 'NATIONAL'
class User(BaseModel):
name: str
phone_number: PhoneNumber