python中validators库的使用方法详解

Python
361
0
0
2023-02-28
标签   Python库
目录
  • 前言
  • validators.between(value, min=None, max=None)
  • validators.domain(value)
  • validators.email(value, whitelist=None)
  • validators.ip_address.ipv4(value) 
  • validators.ip_address.ipv6(value)
  • validators.length(value, min=None, max=None) 
  • validators.mac_address(value) 
  • validators.url(value, public=False) 

前言

首先安装validators库:

pip install validators

validators.between(value, min=None, max=None)

验证一个数字value是否在最小值min和最大值max之间,value不仅仅可以是整数,也可以是其它数据类型,例如floats, decimals 和 dates。

源码解析:

def between(value, min=None, max=None):
    """
    Validate that a number is between minimum and/or maximum value.
    This will work with any comparable type, such as floats, decimals and dates
    not just integers.
    This validator is originally based on `WTForms NumberRange validator`_.
    .. _WTForms NumberRange validator:
       https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
    Examples::
        >>> from datetime import datetime
        >>> between(5, min=2)
        True
        >>> between(13.2, min=13, max=14)
        True
        >>> between(500, max=400)
        ValidationFailure(func=between, args=...)
        >>> between(
        ...     datetime(2000, 11, 11),
        ...     min=datetime(1999, 11, 11)
        ... )
        True
    :param min:
        The minimum required value of the number. If not provided, minimum
        value will not be checked.
    :param max:
        The maximum value of the number. If not provided, maximum value
        will not be checked.
    .. versionadded:: 0.2
    """

示例代码:

from validators import between
from datetime import datetime
 
aa = between(3, min=2)
print(aa)
 
bb = between(3, min=2, max=5)
print(bb)
 
cc = between(3, max=2)
print(cc)
 
dd = between(datetime(2022, 9, 21), min=datetime(2022, 9, 19))
print(dd)
 
ee = between(datetime(2022, 9, 21), min=datetime(2022, 9, 19), max=datetime(2022, 10, 19))
print(ee)
 
ff = between(datetime(2022, 9, 21), max=datetime(2022, 9, 19))
print(ff)

运行结果:

validators.domain(value)

验证value是否是一个有效域。如果value是一个有效域名,函数返回True, 否则返回 ValidationFailure.

源码解析:

def domain(value):
    """
    Return whether or not given value is a valid domain.
    If the value is valid domain name this function returns ``True``, otherwise
    :class:`~validators.utils.ValidationFailure`.
    Examples::
        >>> domain('example.com')
        True
        >>> domain('example.com/')
        ValidationFailure(func=domain, ...)
    Supports IDN domains as well::
        >>> domain('xn----gtbspbbmkef.xn--p1ai')
        True
    .. versionadded:: 0.9
    .. versionchanged:: 0.10
        Added support for internationalized domain name (IDN) validation.
    :param value: domain string to validate
    """

示例代码:

from validators import domain
 
aa = domain('example.com')
print(aa)
 
bb = domain('example..com')
print(bb)

运行结果:

validators.email(value, whitelist=None)

验证是否是合法的邮件地址,如果是,函数返回True, 否则返回 ValidationFailure.

源码解析:

def email(value, whitelist=None):
    """
    Validate an email address.
    This validator is based on `Django's email validator`_. Returns
    ``True`` on success and :class:`~validators.utils.ValidationFailure`
    when validation fails.
    Examples::
        >>> email('someone@example.com')
        True
        >>> email('bogus@@')
        ValidationFailure(func=email, ...)
    .. _Django's email validator:
       https://github.com/django/django/blob/master/django/core/validators.py
    .. versionadded:: 0.1
    :param value: value to validate
    :param whitelist: domain names to whitelist
    :copyright: (c) Django Software Foundation and individual contributors.
    :license: BSD
    """

示例代码:

from validators import email
 
aa = email("123@qq.com")
print(aa)
 
bb = email("123@.com")
print(bb)

运行结果:

validators.ip_address.ipv4(value) 

验证是否是合法的ipv4地址,如果是,函数返回True, 否则返回 ValidationFailure.

源码解析:

def ipv4(value):
    """
    Return whether a given value is a valid IP version 4 address.
    This validator is based on `WTForms IPAddress validator`_
    .. _WTForms IPAddress validator:
       https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
    Examples::
        >>> ipv4('123.0.0.7')
        True
        >>> ipv4('900.80.70.11')
        ValidationFailure(func=ipv4, args={'value': '900.80.70.11'})
    .. versionadded:: 0.2
    :param value: IP address string to validate
    """

示例代码:

from validators.ip_address import ipv4
 
aa = ipv4("127.0.0.1")
print(aa)
 
bb = ipv4("333.1.1.1")
print(bb)

运行结果:

validators.ip_address.ipv6(value)

验证是否是合法的ipv6地址,如果是,函数返回True, 否则返回 ValidationFailure.

源码解析:

def ipv6(value):
    """
    Return whether a given value is a valid IP version 6 address
    (including IPv4-mapped IPv6 addresses).
    This validator is based on `WTForms IPAddress validator`_.
    .. _WTForms IPAddress validator:
       https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
    Examples::
        >>> ipv6('abcd:ef::42:1')
        True
        >>> ipv6('::ffff:192.0.2.128')
        True
        >>> ipv6('::192.0.2.128')
        True
        >>> ipv6('abc.0.0.1')
        ValidationFailure(func=ipv6, args={'value': 'abc.0.0.1'})
    .. versionadded:: 0.2
    :param value: IP address string to validate
    """

示例代码:

from validators.ip_address import ipv6
 
aa = ipv6("abcd:ef::42:1")
print(aa)
 
bb = ipv6("abc.0.0.1")
print(bb)

运行效果:

validators.length(value, min=None, max=None) 

验证给定的字符串长度是否在指定范围内。

示例代码:

from validators import length
 
aa = length('aaa', min=2)
print(aa)
 
bb = length("aaa", min=2, max=5)
print(bb)
 
cc = length("aaa", max=2)
print(cc)

运行结果:

validators.mac_address(value) 

验证是否是合法的mac地址,如果是,函数返回True, 否则返回 ValidationFailure.

示例代码:

from validators import mac_address
 
aa = mac_address('01:23:45:67:ab:CD')
print(aa)
 
bb = mac_address('00:00:00:00:00')
print(bb)

运行结果:

validators.url(value, public=False) 

验证是否是合法的url,如果是,函数返回True, 否则返回 ValidationFailure.

Parameters:

  • value – 要验证的url
  • public – (default=False) Set True to only allow a public IP address

示例代码:

from validators import url
 
aa = url('http://www.baidu.com')
print(aa)
 
bb = url("www.baidu.com")
print(bb)
 
cc = url("http://127.0.0.1")
print(cc)
 
dd = url("http://127.0.0.1", public=True)
print(dd)

运行结果: