repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
JarryShaw/PyPCAPKit | src/protocols/internet/hopopt.py | HOPOPT._read_opt_ip_dff | def _read_opt_ip_dff(self, code, *, desc):
"""Read HOPOPT IP_DFF option.
Structure of HOPOPT IP_DFF option [RFC 6971]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | OptTypeDFF | OptDataLenDFF |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|VER|D|R|0|0|0|0| Sequence Number | Pad1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 hopopt.ip_dff.type Option Type
0 0 hopopt.ip_dff.type.value Option Number
0 0 hopopt.ip_dff.type.action Action (11)
0 2 hopopt.ip_dff.type.change Change Flag (1)
1 8 hopopt.ip_dff.length Length of Option Data
2 16 hopopt.ip_dff.version Version
2 18 hopopt.ip_dff.flags Flags
2 18 hopopt.ip_dff.flags.dup DUP Flag
2 19 hopopt.ip_dff.flags.ret RET Flag
2 20 - Reserved
3 24 hopopt.ip_dff.seq Sequence Number
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_verf = self._read_binary(1)
_seqn = self._read_unpack(2)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
version=_verf[:2],
flags=dict(
dup=True if int(_verf[2], base=2) else False,
ret=True if int(_verf[3], base=2) else False,
),
seq=_seqn,
)
return opt | python | def _read_opt_ip_dff(self, code, *, desc):
"""Read HOPOPT IP_DFF option.
Structure of HOPOPT IP_DFF option [RFC 6971]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | OptTypeDFF | OptDataLenDFF |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|VER|D|R|0|0|0|0| Sequence Number | Pad1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 hopopt.ip_dff.type Option Type
0 0 hopopt.ip_dff.type.value Option Number
0 0 hopopt.ip_dff.type.action Action (11)
0 2 hopopt.ip_dff.type.change Change Flag (1)
1 8 hopopt.ip_dff.length Length of Option Data
2 16 hopopt.ip_dff.version Version
2 18 hopopt.ip_dff.flags Flags
2 18 hopopt.ip_dff.flags.dup DUP Flag
2 19 hopopt.ip_dff.flags.ret RET Flag
2 20 - Reserved
3 24 hopopt.ip_dff.seq Sequence Number
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_verf = self._read_binary(1)
_seqn = self._read_unpack(2)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
version=_verf[:2],
flags=dict(
dup=True if int(_verf[2], base=2) else False,
ret=True if int(_verf[3], base=2) else False,
),
seq=_seqn,
)
return opt | Read HOPOPT IP_DFF option.
Structure of HOPOPT IP_DFF option [RFC 6971]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | OptTypeDFF | OptDataLenDFF |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|VER|D|R|0|0|0|0| Sequence Number | Pad1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 hopopt.ip_dff.type Option Type
0 0 hopopt.ip_dff.type.value Option Number
0 0 hopopt.ip_dff.type.action Action (11)
0 2 hopopt.ip_dff.type.change Change Flag (1)
1 8 hopopt.ip_dff.length Length of Option Data
2 16 hopopt.ip_dff.version Version
2 18 hopopt.ip_dff.flags Flags
2 18 hopopt.ip_dff.flags.dup DUP Flag
2 19 hopopt.ip_dff.flags.ret RET Flag
2 20 - Reserved
3 24 hopopt.ip_dff.seq Sequence Number | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hopopt.py#L1016-L1061 |
JarryShaw/PyPCAPKit | src/const/ipx/socket.py | Socket.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Socket(key)
if key not in Socket._member_map_:
extend_enum(Socket, key, default)
return Socket[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Socket(key)
if key not in Socket._member_map_:
extend_enum(Socket, key, default)
return Socket[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipx/socket.py#L28-L34 |
JarryShaw/PyPCAPKit | src/const/ipx/socket.py | Socket._missing_ | def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 0x0001 <= value <= 0x0BB8:
extend_enum(cls, 'Registered by Xerox [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0020 <= value <= 0x003F:
extend_enum(cls, 'Experimental [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0BB9 <= value <= 0xFFFF:
extend_enum(cls, 'Dynamically Assigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x4000 <= value <= 0x4FFF:
extend_enum(cls, 'Dynamically Assigned Socket Numbers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8000 <= value <= 0xFFFF:
extend_enum(cls, 'Statically Assigned Socket Numbers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
super()._missing_(value) | python | def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 0x0001 <= value <= 0x0BB8:
extend_enum(cls, 'Registered by Xerox [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0020 <= value <= 0x003F:
extend_enum(cls, 'Experimental [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0BB9 <= value <= 0xFFFF:
extend_enum(cls, 'Dynamically Assigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x4000 <= value <= 0x4FFF:
extend_enum(cls, 'Dynamically Assigned Socket Numbers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8000 <= value <= 0xFFFF:
extend_enum(cls, 'Statically Assigned Socket Numbers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
super()._missing_(value) | Lookup function used when value is not found. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipx/socket.py#L37-L56 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_opts.py | IPv6_Opts.read_ipv6_opts | def read_ipv6_opts(self, length, extension):
"""Read Destination Options for IPv6.
Structure of IPv6-Opts header [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| |
. .
. Options .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 opt.next Next Header
1 8 opt.length Header Extensive Length
2 16 opt.options Options
"""
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
# _opts = self._read_fileng(_hlen*8+6)
ipv6_opts = dict(
next=_next,
length=(_hlen + 1) * 8,
)
options = self._read_ipv6_opts_options(_hlen * 8 + 6)
ipv6_opts['options'] = options[0] # tuple of option acronyms
ipv6_opts.update(options[1]) # merge option info to buffer
length -= ipv6_opts['length']
ipv6_opts['packet'] = self._read_packet(header=ipv6_opts['length'], payload=length)
if extension:
self._protos = None
return ipv6_opts
return self._decode_next_layer(ipv6_opts, _next, length) | python | def read_ipv6_opts(self, length, extension):
"""Read Destination Options for IPv6.
Structure of IPv6-Opts header [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| |
. .
. Options .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 opt.next Next Header
1 8 opt.length Header Extensive Length
2 16 opt.options Options
"""
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
# _opts = self._read_fileng(_hlen*8+6)
ipv6_opts = dict(
next=_next,
length=(_hlen + 1) * 8,
)
options = self._read_ipv6_opts_options(_hlen * 8 + 6)
ipv6_opts['options'] = options[0] # tuple of option acronyms
ipv6_opts.update(options[1]) # merge option info to buffer
length -= ipv6_opts['length']
ipv6_opts['packet'] = self._read_packet(header=ipv6_opts['length'], payload=length)
if extension:
self._protos = None
return ipv6_opts
return self._decode_next_layer(ipv6_opts, _next, length) | Read Destination Options for IPv6.
Structure of IPv6-Opts header [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| |
. .
. Options .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 opt.next Next Header
1 8 opt.length Header Extensive Length
2 16 opt.options Options | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L152-L194 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_opts.py | IPv6_Opts._read_opt_type | def _read_opt_type(self, kind):
"""Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits Name Descriptions
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1)
"""
bin_ = bin(kind)[2:].zfill(8)
type_ = dict(
value=kind,
action=_IPv6_Opts_ACT.get(bin_[:2]),
change=True if int(bin_[2], base=2) else False,
)
return type_ | python | def _read_opt_type(self, kind):
"""Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits Name Descriptions
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1)
"""
bin_ = bin(kind)[2:].zfill(8)
type_ = dict(
value=kind,
action=_IPv6_Opts_ACT.get(bin_[:2]),
change=True if int(bin_[2], base=2) else False,
)
return type_ | Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv6_Opts option
Structure of option type field [RFC 791]:
Octets Bits Name Descriptions
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1) | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L212-L235 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_opts.py | IPv6_Opts._read_ipv6_opts_options | def _read_ipv6_opts_options(self, length):
"""Read IPv6_Opts options.
Positional arguments:
* length -- int, length of options
Returns:
* dict -- extracted IPv6_Opts options
"""
counter = 0 # length of read options
optkind = list() # option type list
options = dict() # dict of option data
while counter < length:
# break when eol triggered
code = self._read_unpack(1)
if not code:
break
# extract parameter
abbr, desc = _IPv6_Opts_OPT.get(code, ('None', 'Unassigned'))
data = _IPv6_Opts_PROC(abbr)(self, code, desc=desc)
enum = _OPT_TYPE.get(code)
# record parameter data
counter += data['length']
if enum in optkind:
if isinstance(options[abbr], tuple):
options[abbr] += (Info(data),)
else:
options[abbr] = (Info(options[abbr]), Info(data))
else:
optkind.append(enum)
options[abbr] = data
# check threshold
if counter != length:
raise ProtocolError(f'{self.alias}: invalid format')
return tuple(optkind), options | python | def _read_ipv6_opts_options(self, length):
"""Read IPv6_Opts options.
Positional arguments:
* length -- int, length of options
Returns:
* dict -- extracted IPv6_Opts options
"""
counter = 0 # length of read options
optkind = list() # option type list
options = dict() # dict of option data
while counter < length:
# break when eol triggered
code = self._read_unpack(1)
if not code:
break
# extract parameter
abbr, desc = _IPv6_Opts_OPT.get(code, ('None', 'Unassigned'))
data = _IPv6_Opts_PROC(abbr)(self, code, desc=desc)
enum = _OPT_TYPE.get(code)
# record parameter data
counter += data['length']
if enum in optkind:
if isinstance(options[abbr], tuple):
options[abbr] += (Info(data),)
else:
options[abbr] = (Info(options[abbr]), Info(data))
else:
optkind.append(enum)
options[abbr] = data
# check threshold
if counter != length:
raise ProtocolError(f'{self.alias}: invalid format')
return tuple(optkind), options | Read IPv6_Opts options.
Positional arguments:
* length -- int, length of options
Returns:
* dict -- extracted IPv6_Opts options | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L237-L277 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_opts.py | IPv6_Opts._read_opt_none | def _read_opt_none(self, code, *, desc):
"""Read IPv6_Opts unassigned options.
Structure of IPv6_Opts unassigned options [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
| Option Type | Opt Data Len | Option Data
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
Octets Bits Name Description
0 0 ipv6_opts.opt.type Option Type
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1)
1 8 ipv6_opts.opt.length Length of Option Data
2 16 ipv6_opts.opt.data Option Data
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_data = self._read_fileng(_size)
opt = dict(
desc=_IPv6_Opts_NULL.get(code, desc),
type=_type,
length=_size + 2,
data=_data,
)
return opt | python | def _read_opt_none(self, code, *, desc):
"""Read IPv6_Opts unassigned options.
Structure of IPv6_Opts unassigned options [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
| Option Type | Opt Data Len | Option Data
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
Octets Bits Name Description
0 0 ipv6_opts.opt.type Option Type
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1)
1 8 ipv6_opts.opt.length Length of Option Data
2 16 ipv6_opts.opt.data Option Data
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_data = self._read_fileng(_size)
opt = dict(
desc=_IPv6_Opts_NULL.get(code, desc),
type=_type,
length=_size + 2,
data=_data,
)
return opt | Read IPv6_Opts unassigned options.
Structure of IPv6_Opts unassigned options [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
| Option Type | Opt Data Len | Option Data
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - -
Octets Bits Name Description
0 0 ipv6_opts.opt.type Option Type
0 0 ipv6_opts.opt.type.value Option Number
0 0 ipv6_opts.opt.type.action Action (00-11)
0 2 ipv6_opts.opt.type.change Change Flag (0/1)
1 8 ipv6_opts.opt.length Length of Option Data
2 16 ipv6_opts.opt.data Option Data | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L279-L307 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_opts.py | IPv6_Opts._read_opt_mpl | def _read_opt_mpl(self, code, *, desc):
"""Read IPv6_Opts MPL option.
Structure of IPv6_Opts MPL option [RFC 7731]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| S |M|V| rsv | sequence | seed-id (optional) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ipv6_opts.mpl.type Option Type
0 0 ipv6_opts.mpl.type.value Option Number
0 0 ipv6_opts.mpl.type.action Action (01)
0 2 ipv6_opts.mpl.type.change Change Flag (1)
1 8 ipv6_opts.mpl.length Length of Option Data
2 16 ipv6_opts.mpl.seed_len Seed-ID Length
2 18 ipv6_opts.mpl.flags MPL Option Flags
2 18 ipv6_opts.mpl.max Maximum SEQ Flag
2 19 ipv6_opts.mpl.verification Verification Flag
2 20 - Reserved
3 24 ipv6_opts.mpl.seq Sequence
4 32 ipv6_opts.mpl.seed_id Seed-ID
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size < 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_smvr = self._read_binary(1)
_seqn = self._read_unpack(1)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
seed_len=_IPv6_Opts_SEED.get(int(_smvr[:2], base=2)),
flags=dict(
max=True if int(_smvr[2], base=2) else False,
verification=True if int(_smvr[3], base=2) else False,
),
seq=_seqn,
)
_kind = _smvr[:2]
if _kind == '00':
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
elif _kind == '01':
if _size != 4:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(2)
elif _kind == '10':
if _size != 10:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(8)
elif _kind == '11':
if _size != 18:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(16)
else:
opt['seed_id'] = self._read_unpack(_size-2)
_plen = _size - opt['seed_len']
if _plen:
self._read_fileng(_plen)
return opt | python | def _read_opt_mpl(self, code, *, desc):
"""Read IPv6_Opts MPL option.
Structure of IPv6_Opts MPL option [RFC 7731]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| S |M|V| rsv | sequence | seed-id (optional) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ipv6_opts.mpl.type Option Type
0 0 ipv6_opts.mpl.type.value Option Number
0 0 ipv6_opts.mpl.type.action Action (01)
0 2 ipv6_opts.mpl.type.change Change Flag (1)
1 8 ipv6_opts.mpl.length Length of Option Data
2 16 ipv6_opts.mpl.seed_len Seed-ID Length
2 18 ipv6_opts.mpl.flags MPL Option Flags
2 18 ipv6_opts.mpl.max Maximum SEQ Flag
2 19 ipv6_opts.mpl.verification Verification Flag
2 20 - Reserved
3 24 ipv6_opts.mpl.seq Sequence
4 32 ipv6_opts.mpl.seed_id Seed-ID
"""
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
if _size < 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
_type = self._read_opt_type(code)
_size = self._read_unpack(1)
_smvr = self._read_binary(1)
_seqn = self._read_unpack(1)
opt = dict(
desc=desc,
type=_type,
length=_size + 2,
seed_len=_IPv6_Opts_SEED.get(int(_smvr[:2], base=2)),
flags=dict(
max=True if int(_smvr[2], base=2) else False,
verification=True if int(_smvr[3], base=2) else False,
),
seq=_seqn,
)
_kind = _smvr[:2]
if _kind == '00':
if _size != 2:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
elif _kind == '01':
if _size != 4:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(2)
elif _kind == '10':
if _size != 10:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(8)
elif _kind == '11':
if _size != 18:
raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format')
opt['seed_id'] = self._read_unpack(16)
else:
opt['seed_id'] = self._read_unpack(_size-2)
_plen = _size - opt['seed_len']
if _plen:
self._read_fileng(_plen)
return opt | Read IPv6_Opts MPL option.
Structure of IPv6_Opts MPL option [RFC 7731]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| S |M|V| rsv | sequence | seed-id (optional) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ipv6_opts.mpl.type Option Type
0 0 ipv6_opts.mpl.type.value Option Number
0 0 ipv6_opts.mpl.type.action Action (01)
0 2 ipv6_opts.mpl.type.change Change Flag (1)
1 8 ipv6_opts.mpl.length Length of Option Data
2 16 ipv6_opts.mpl.seed_len Seed-ID Length
2 18 ipv6_opts.mpl.flags MPL Option Flags
2 18 ipv6_opts.mpl.max Maximum SEQ Flag
2 19 ipv6_opts.mpl.verification Verification Flag
2 20 - Reserved
3 24 ipv6_opts.mpl.seq Sequence
4 32 ipv6_opts.mpl.seed_id Seed-ID | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_opts.py#L797-L869 |
JarryShaw/PyPCAPKit | src/const/ftp/return_code.py | ReturnCode.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ReturnCode(key)
if key not in ReturnCode._member_map_:
extend_enum(ReturnCode, key, default)
return ReturnCode[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ReturnCode(key)
if key not in ReturnCode._member_map_:
extend_enum(ReturnCode, key, default)
return ReturnCode[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ftp/return_code.py#L80-L86 |
JarryShaw/PyPCAPKit | src/const/ftp/return_code.py | ReturnCode._missing_ | def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 100 <= value <= 659):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
code = str(value)
kind = KIND.get(code[0], 'Reserved')
info = INFO.get(code[1], 'Reserved')
extend_enum(cls, '%s - %s [%s]' % (kind, info, value), value)
return cls(value) | python | def _missing_(cls, value):
"""Lookup function used when value is not found."""
if not (isinstance(value, int) and 100 <= value <= 659):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
code = str(value)
kind = KIND.get(code[0], 'Reserved')
info = INFO.get(code[1], 'Reserved')
extend_enum(cls, '%s - %s [%s]' % (kind, info, value), value)
return cls(value) | Lookup function used when value is not found. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ftp/return_code.py#L89-L97 |
JarryShaw/PyPCAPKit | src/const/hip/cipher.py | Cipher.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Cipher(key)
if key not in Cipher._member_map_:
extend_enum(Cipher, key, default)
return Cipher[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Cipher(key)
if key not in Cipher._member_map_:
extend_enum(Cipher, key, default)
return Cipher[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/cipher.py#L19-L25 |
JarryShaw/PyPCAPKit | src/const/mh/packet.py | Packet.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
extend_enum(Packet, key, default)
return Packet[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Packet(key)
if key not in Packet._member_map_:
extend_enum(Packet, key, default)
return Packet[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/mh/packet.py#L38-L44 |
JarryShaw/PyPCAPKit | src/const/ipv6/option.py | Option.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
return Option[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Option(key)
if key not in Option._member_map_:
extend_enum(Option, key, default)
return Option[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/option.py#L39-L45 |
JarryShaw/PyPCAPKit | src/const/ipv6/extension_header.py | ExtensionHeader.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ExtensionHeader(key)
if key not in ExtensionHeader._member_map_:
extend_enum(ExtensionHeader, key, default)
return ExtensionHeader[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ExtensionHeader(key)
if key not in ExtensionHeader._member_map_:
extend_enum(ExtensionHeader, key, default)
return ExtensionHeader[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/extension_header.py#L25-L31 |
JarryShaw/PyPCAPKit | src/const/ipv4/option_class.py | OptionClass.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return OptionClass(key)
if key not in OptionClass._member_map_:
extend_enum(OptionClass, key, default)
return OptionClass[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return OptionClass(key)
if key not in OptionClass._member_map_:
extend_enum(OptionClass, key, default)
return OptionClass[key] | Backport support for original codes. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/option_class.py#L18-L24 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_route.py | IPv6_Route.read_ipv6_route | def read_ipv6_route(self, length, extension):
"""Read Routing Header for IPv6.
Structure of IPv6-Route header [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
_type = self._read_unpack(1)
_left = self._read_unpack(1)
ipv6_route = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_ROUTING_TYPE.get(_type, 'Unassigned'),
seg_left=_left,
)
_dlen = _hlen * 8 - 4
if _dlen:
_func = _ROUTE_PROC.get(_type, 'none')
_data = eval(f'self._read_data_type_{_func}')(_dlen)
ipv6_route.update(_data)
length -= ipv6_route['length']
ipv6_route['packet'] = self._read_packet(header=ipv6_route['length'], payload=length)
if extension:
self._protos = None
return ipv6_route
return self._decode_next_layer(ipv6_route, _next, length) | python | def read_ipv6_route(self, length, extension):
"""Read Routing Header for IPv6.
Structure of IPv6-Route header [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
_type = self._read_unpack(1)
_left = self._read_unpack(1)
ipv6_route = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_ROUTING_TYPE.get(_type, 'Unassigned'),
seg_left=_left,
)
_dlen = _hlen * 8 - 4
if _dlen:
_func = _ROUTE_PROC.get(_type, 'none')
_data = eval(f'self._read_data_type_{_func}')(_dlen)
ipv6_route.update(_data)
length -= ipv6_route['length']
ipv6_route['packet'] = self._read_packet(header=ipv6_route['length'], payload=length)
if extension:
self._protos = None
return ipv6_route
return self._decode_next_layer(ipv6_route, _next, length) | Read Routing Header for IPv6.
Structure of IPv6-Route header [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L102-L151 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_route.py | IPv6_Route._read_data_type_none | def _read_data_type_none(self, length):
"""Read IPv6-Route unknown type data.
Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
_data = self._read_fileng(length)
data = dict(
data=_data,
)
return data | python | def _read_data_type_none(self, length):
"""Read IPv6-Route unknown type data.
Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data
"""
_data = self._read_fileng(length)
data = dict(
data=_data,
)
return data | Read IPv6-Route unknown type data.
Structure of IPv6-Route unknown type data [RFC 8200][RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. type-specific data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.data Type-Specific Data | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L169-L197 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_route.py | IPv6_Route._read_data_type_src | def _read_data_type_src(self, length):
"""Read IPv6-Route Source Route data.
Structure of IPv6-Route Source Route data [RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type=0| Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Address
............
"""
_resv = self._read_fileng(4)
_addr = list()
for _ in range((length - 4) // 16):
_addr.append(ipaddress.ip_address(self._read_fileng(16)))
data = dict(
ip=tuple(_addr),
)
return data | python | def _read_data_type_src(self, length):
"""Read IPv6-Route Source Route data.
Structure of IPv6-Route Source Route data [RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type=0| Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Address
............
"""
_resv = self._read_fileng(4)
_addr = list()
for _ in range((length - 4) // 16):
_addr.append(ipaddress.ip_address(self._read_fileng(16)))
data = dict(
ip=tuple(_addr),
)
return data | Read IPv6-Route Source Route data.
Structure of IPv6-Route Source Route data [RFC 5095]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type=0| Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[1] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[2] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. . .
. . .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Address[n] +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Address
............ | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L199-L256 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_route.py | IPv6_Route._read_data_type_2 | def _read_data_type_2(self, length):
"""Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Home Address
"""
if length != 20:
raise ProtocolError(f'{self.alias}: [Typeno 2] invalid format')
_resv = self._read_fileng(4)
_home = self._read_fileng(16)
data = dict(
ip=ipaddress.ip_address(_home),
)
return data | python | def _read_data_type_2(self, length):
"""Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Home Address
"""
if length != 20:
raise ProtocolError(f'{self.alias}: [Typeno 2] invalid format')
_resv = self._read_fileng(4)
_home = self._read_fileng(16)
data = dict(
ip=ipaddress.ip_address(_home),
)
return data | Read IPv6-Route Type 2 data.
Structure of IPv6-Route Type 2 data [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len=2 | Routing Type=2|Segments Left=1|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Home Address +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 - Reserved
8 64 route.ip Home Address | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L258-L295 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipv6_route.py | IPv6_Route._read_data_type_rpl | def _read_data_type_rpl(self, length):
"""Read IPv6-Route RPL Source data.
Structure of IPv6-Route RPL Source data [RFC 6554]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CmprI | CmprE | Pad | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. Addresses[1..n] .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.cmpri CmprI
4 36 route.cpmre CmprE
5 40 route.pad Pad Size
5 44 - Reserved
8 64 route.ip Addresses
"""
_cmpr = self._read_binary(1)
_padr = self._read_binary(1)
_resv = self._read_fileng(2)
_inti = int(_cmpr[:4], base=2)
_inte = int(_cmpr[4:], base=2)
_plen = int(_padr[:4], base=2)
_ilen = 16 - _inti
_elen = 16 - _inte
_addr = list()
for _ in (((length - 4) - _elen - _plen) // _ilen):
_addr.append(ipaddress.ip_address(self._read_fileng(_ilen)))
_addr.append(ipaddress.ip_address(self._read_fileng(_elen)))
_pads = self._read_fileng(_plen)
data = dict(
cmpri=_inti,
cmpre=_inte,
pad=_plen,
ip=tuple(_addr),
)
return data | python | def _read_data_type_rpl(self, length):
"""Read IPv6-Route RPL Source data.
Structure of IPv6-Route RPL Source data [RFC 6554]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CmprI | CmprE | Pad | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. Addresses[1..n] .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.cmpri CmprI
4 36 route.cpmre CmprE
5 40 route.pad Pad Size
5 44 - Reserved
8 64 route.ip Addresses
"""
_cmpr = self._read_binary(1)
_padr = self._read_binary(1)
_resv = self._read_fileng(2)
_inti = int(_cmpr[:4], base=2)
_inte = int(_cmpr[4:], base=2)
_plen = int(_padr[:4], base=2)
_ilen = 16 - _inti
_elen = 16 - _inte
_addr = list()
for _ in (((length - 4) - _elen - _plen) // _ilen):
_addr.append(ipaddress.ip_address(self._read_fileng(_ilen)))
_addr.append(ipaddress.ip_address(self._read_fileng(_elen)))
_pads = self._read_fileng(_plen)
data = dict(
cmpri=_inti,
cmpre=_inte,
pad=_plen,
ip=tuple(_addr),
)
return data | Read IPv6-Route RPL Source data.
Structure of IPv6-Route RPL Source data [RFC 6554]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Hdr Ext Len | Routing Type | Segments Left |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| CmprI | CmprE | Pad | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
. .
. Addresses[1..n] .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 route.next Next Header
1 8 route.length Header Extensive Length
2 16 route.type Routing Type
3 24 route.seg_left Segments Left
4 32 route.cmpri CmprI
4 36 route.cpmre CmprE
5 40 route.pad Pad Size
5 44 - Reserved
8 64 route.ip Addresses | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipv6_route.py#L297-L352 |
JarryShaw/PyPCAPKit | src/protocols/application/httpv1.py | HTTPv1.read_http | def read_http(self, length):
"""Read Hypertext Transfer Protocol (HTTP/1.*).
Structure of HTTP/1.* packet [RFC 7230]:
HTTP-message :==: start-line
*( header-field CRLF )
CRLF
[ message-body ]
"""
if length is None:
length = len(self)
packet = self._file.read(length)
try:
header, body = packet.split(b'\r\n\r\n', 1)
except ValueError:
raise ProtocolError('HTTP: invalid format', quiet=True)
header_unpacked, http_receipt = self._read_http_header(header)
body_unpacked = self._read_http_body(body) or None
http = dict(
receipt=http_receipt,
header=header_unpacked,
body=body_unpacked,
raw=dict(
header=header,
body=body,
packet=self._read_packet(length),
),
)
self.__receipt__ = http_receipt
return http | python | def read_http(self, length):
"""Read Hypertext Transfer Protocol (HTTP/1.*).
Structure of HTTP/1.* packet [RFC 7230]:
HTTP-message :==: start-line
*( header-field CRLF )
CRLF
[ message-body ]
"""
if length is None:
length = len(self)
packet = self._file.read(length)
try:
header, body = packet.split(b'\r\n\r\n', 1)
except ValueError:
raise ProtocolError('HTTP: invalid format', quiet=True)
header_unpacked, http_receipt = self._read_http_header(header)
body_unpacked = self._read_http_body(body) or None
http = dict(
receipt=http_receipt,
header=header_unpacked,
body=body_unpacked,
raw=dict(
header=header,
body=body,
packet=self._read_packet(length),
),
)
self.__receipt__ = http_receipt
return http | Read Hypertext Transfer Protocol (HTTP/1.*).
Structure of HTTP/1.* packet [RFC 7230]:
HTTP-message :==: start-line
*( header-field CRLF )
CRLF
[ message-body ] | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv1.py#L76-L110 |
JarryShaw/PyPCAPKit | src/protocols/application/httpv1.py | HTTPv1._read_http_header | def _read_http_header(self, header):
"""Read HTTP/1.* header.
Structure of HTTP/1.* header [RFC 7230]:
start-line :==: request-line / status-line
request-line :==: method SP request-target SP HTTP-version CRLF
status-line :==: HTTP-version SP status-code SP reason-phrase CRLF
header-field :==: field-name ":" OWS field-value OWS
"""
try:
startline, headerfield = header.split(b'\r\n', 1)
para1, para2, para3 = re.split(rb'\s+', startline, 2)
fields = headerfield.split(b'\r\n')
lists = (re.split(rb'\s*:\s*', field, 1) for field in fields)
except ValueError:
raise ProtocolError('HTTP: invalid format', quiet=True)
match1 = re.match(_RE_METHOD, para1)
match2 = re.match(_RE_VERSION, para3)
match3 = re.match(_RE_VERSION, para1)
match4 = re.match(_RE_STATUS, para2)
if match1 and match2:
receipt = 'request'
header = dict(
request=dict(
method=self.decode(para1),
target=self.decode(para2),
version=self.decode(match2.group('version')),
),
)
elif match3 and match4:
receipt = 'response'
header = dict(
response=dict(
version=self.decode(match3.group('version')),
status=int(para2),
phrase=self.decode(para3),
),
)
else:
raise ProtocolError('HTTP: invalid format', quiet=True)
try:
for item in lists:
key = self.decode(item[0].strip()).replace(receipt, f'{receipt}_field')
value = self.decode(item[1].strip())
if key in header:
if isinstance(header[key], tuple):
header[key] += (value,)
else:
header[key] = (header[key], value)
else:
header[key] = value
except IndexError:
raise ProtocolError('HTTP: invalid format', quiet=True)
return header, receipt | python | def _read_http_header(self, header):
"""Read HTTP/1.* header.
Structure of HTTP/1.* header [RFC 7230]:
start-line :==: request-line / status-line
request-line :==: method SP request-target SP HTTP-version CRLF
status-line :==: HTTP-version SP status-code SP reason-phrase CRLF
header-field :==: field-name ":" OWS field-value OWS
"""
try:
startline, headerfield = header.split(b'\r\n', 1)
para1, para2, para3 = re.split(rb'\s+', startline, 2)
fields = headerfield.split(b'\r\n')
lists = (re.split(rb'\s*:\s*', field, 1) for field in fields)
except ValueError:
raise ProtocolError('HTTP: invalid format', quiet=True)
match1 = re.match(_RE_METHOD, para1)
match2 = re.match(_RE_VERSION, para3)
match3 = re.match(_RE_VERSION, para1)
match4 = re.match(_RE_STATUS, para2)
if match1 and match2:
receipt = 'request'
header = dict(
request=dict(
method=self.decode(para1),
target=self.decode(para2),
version=self.decode(match2.group('version')),
),
)
elif match3 and match4:
receipt = 'response'
header = dict(
response=dict(
version=self.decode(match3.group('version')),
status=int(para2),
phrase=self.decode(para3),
),
)
else:
raise ProtocolError('HTTP: invalid format', quiet=True)
try:
for item in lists:
key = self.decode(item[0].strip()).replace(receipt, f'{receipt}_field')
value = self.decode(item[1].strip())
if key in header:
if isinstance(header[key], tuple):
header[key] += (value,)
else:
header[key] = (header[key], value)
else:
header[key] = value
except IndexError:
raise ProtocolError('HTTP: invalid format', quiet=True)
return header, receipt | Read HTTP/1.* header.
Structure of HTTP/1.* header [RFC 7230]:
start-line :==: request-line / status-line
request-line :==: method SP request-target SP HTTP-version CRLF
status-line :==: HTTP-version SP status-code SP reason-phrase CRLF
header-field :==: field-name ":" OWS field-value OWS | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/application/httpv1.py#L127-L184 |
Bonsanto/polygon-geohasher | polygon_geohasher/polygon_geohasher.py | geohash_to_polygon | def geohash_to_polygon(geo):
"""
:param geo: String that represents the geohash.
:return: Returns a Shapely's Polygon instance that represents the geohash.
"""
lat_centroid, lng_centroid, lat_offset, lng_offset = geohash.decode_exactly(geo)
corner_1 = (lat_centroid - lat_offset, lng_centroid - lng_offset)[::-1]
corner_2 = (lat_centroid - lat_offset, lng_centroid + lng_offset)[::-1]
corner_3 = (lat_centroid + lat_offset, lng_centroid + lng_offset)[::-1]
corner_4 = (lat_centroid + lat_offset, lng_centroid - lng_offset)[::-1]
return geometry.Polygon([corner_1, corner_2, corner_3, corner_4, corner_1]) | python | def geohash_to_polygon(geo):
"""
:param geo: String that represents the geohash.
:return: Returns a Shapely's Polygon instance that represents the geohash.
"""
lat_centroid, lng_centroid, lat_offset, lng_offset = geohash.decode_exactly(geo)
corner_1 = (lat_centroid - lat_offset, lng_centroid - lng_offset)[::-1]
corner_2 = (lat_centroid - lat_offset, lng_centroid + lng_offset)[::-1]
corner_3 = (lat_centroid + lat_offset, lng_centroid + lng_offset)[::-1]
corner_4 = (lat_centroid + lat_offset, lng_centroid - lng_offset)[::-1]
return geometry.Polygon([corner_1, corner_2, corner_3, corner_4, corner_1]) | :param geo: String that represents the geohash.
:return: Returns a Shapely's Polygon instance that represents the geohash. | https://github.com/Bonsanto/polygon-geohasher/blob/63f27f41ea3e9d8fda7872d86217719286037c11/polygon_geohasher/polygon_geohasher.py#L8-L20 |
Bonsanto/polygon-geohasher | polygon_geohasher/polygon_geohasher.py | polygon_to_geohashes | def polygon_to_geohashes(polygon, precision, inner=True):
"""
:param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set of geohashes that form the polygon.
"""
inner_geohashes = set()
outer_geohashes = set()
envelope = polygon.envelope
centroid = polygon.centroid
testing_geohashes = queue.Queue()
testing_geohashes.put(geohash.encode(centroid.y, centroid.x, precision))
while not testing_geohashes.empty():
current_geohash = testing_geohashes.get()
if current_geohash not in inner_geohashes and current_geohash not in outer_geohashes:
current_polygon = geohash_to_polygon(current_geohash)
condition = envelope.contains(current_polygon) if inner else envelope.intersects(current_polygon)
if condition:
if inner:
if polygon.contains(current_polygon):
inner_geohashes.add(current_geohash)
else:
outer_geohashes.add(current_geohash)
else:
if polygon.intersects(current_polygon):
inner_geohashes.add(current_geohash)
else:
outer_geohashes.add(current_geohash)
for neighbor in geohash.neighbors(current_geohash):
if neighbor not in inner_geohashes and neighbor not in outer_geohashes:
testing_geohashes.put(neighbor)
return inner_geohashes | python | def polygon_to_geohashes(polygon, precision, inner=True):
"""
:param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set of geohashes that form the polygon.
"""
inner_geohashes = set()
outer_geohashes = set()
envelope = polygon.envelope
centroid = polygon.centroid
testing_geohashes = queue.Queue()
testing_geohashes.put(geohash.encode(centroid.y, centroid.x, precision))
while not testing_geohashes.empty():
current_geohash = testing_geohashes.get()
if current_geohash not in inner_geohashes and current_geohash not in outer_geohashes:
current_polygon = geohash_to_polygon(current_geohash)
condition = envelope.contains(current_polygon) if inner else envelope.intersects(current_polygon)
if condition:
if inner:
if polygon.contains(current_polygon):
inner_geohashes.add(current_geohash)
else:
outer_geohashes.add(current_geohash)
else:
if polygon.intersects(current_polygon):
inner_geohashes.add(current_geohash)
else:
outer_geohashes.add(current_geohash)
for neighbor in geohash.neighbors(current_geohash):
if neighbor not in inner_geohashes and neighbor not in outer_geohashes:
testing_geohashes.put(neighbor)
return inner_geohashes | :param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set of geohashes that form the polygon. | https://github.com/Bonsanto/polygon-geohasher/blob/63f27f41ea3e9d8fda7872d86217719286037c11/polygon_geohasher/polygon_geohasher.py#L23-L62 |
desbma/r128gain | r128gain/opusgain.py | parse_oggopus_output_gain | def parse_oggopus_output_gain(file):
""" Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header. """
#
# Ogg header
#
# check fields of Ogg page header
chunk = file.read(OGG_FIRST_PAGE_HEADER.size)
first_ogg_page = bytearray()
first_ogg_page.extend(chunk)
if len(chunk) < OGG_FIRST_PAGE_HEADER.size:
logger().error("Not enough bytes in Ogg page header: %u, expected at least %u" % (len(chunk),
OGG_FIRST_PAGE_HEADER.size))
return
capture_pattern, version, header_type, granule_position, bitstream_serial_number, page_sequence_number, \
crc_checksum, page_segments = OGG_FIRST_PAGE_HEADER.unpack(chunk)
if capture_pattern != b"OggS":
logger().error("Invalid OGG capture pattern: %s, expected '%s'" % (repr(capture_pattern), "OggS"))
return
if version != 0:
logger().error("Invalid OGG version: %u, expected %u" % (version, 0))
return
if header_type != 2: # should be first page of stream
logger().error("Invalid OGG page header type: %u, expected %u" % (header_type, 2))
return
if page_sequence_number != 0:
logger().error("Invalid OGG page sequence number: %u, expected %u" % (page_sequence_number, 0))
return
segment_table_fmt = struct.Struct("<%uB" % (page_segments))
chunk = file.read(segment_table_fmt.size)
first_ogg_page.extend(chunk)
if len(chunk) < segment_table_fmt.size:
logger().error("Not enough bytes for OGG segment table: %u, expected at least %u" % (len(chunk),
segment_table_fmt.size))
return
segment_table = segment_table_fmt.unpack(chunk)
# check crc of first page
first_ogg_page_size = OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size + sum(segment_table)
chunk = file.read(sum(segment_table))
first_ogg_page.extend(chunk)
if len(first_ogg_page) < first_ogg_page_size:
logger().error("Not enough bytes for first OGG page: %u, expected at least %u" % (len(first_ogg_page),
first_ogg_page_size))
return
computed_crc = _compute_ogg_page_crc(first_ogg_page)
if computed_crc != crc_checksum:
logger().error("Invalid OGG page CRC: 0x%08x, expected 0x%08x" % (crc_checksum, computed_crc))
return
#
# Opus header
#
chunk = first_ogg_page[OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size:][:segment_table[0]]
if len(chunk) < OGG_OPUS_ID_HEADER.size:
logger().error("Not enough bytes for Opus Identification header: %u, "
"expected at least %u" % (len(chunk),
OGG_OPUS_ID_HEADER.size))
return
magic, version, channel_count, preskip, input_samplerate, output_gain, \
mapping_family = OGG_OPUS_ID_HEADER.unpack(chunk[:OGG_OPUS_ID_HEADER.size])
if magic != b"OpusHead":
logger().error("Invalid Opus magic number: %s, expected '%s'" % (repr(magic), "OpusHead"))
return
if (version >> 4) != 0:
logger().error("Invalid Opus version: 0x%x, expected 0x0-0xf" % (version))
return
# seek to Opus header
file.seek(OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size)
return output_gain | python | def parse_oggopus_output_gain(file):
""" Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header. """
#
# Ogg header
#
# check fields of Ogg page header
chunk = file.read(OGG_FIRST_PAGE_HEADER.size)
first_ogg_page = bytearray()
first_ogg_page.extend(chunk)
if len(chunk) < OGG_FIRST_PAGE_HEADER.size:
logger().error("Not enough bytes in Ogg page header: %u, expected at least %u" % (len(chunk),
OGG_FIRST_PAGE_HEADER.size))
return
capture_pattern, version, header_type, granule_position, bitstream_serial_number, page_sequence_number, \
crc_checksum, page_segments = OGG_FIRST_PAGE_HEADER.unpack(chunk)
if capture_pattern != b"OggS":
logger().error("Invalid OGG capture pattern: %s, expected '%s'" % (repr(capture_pattern), "OggS"))
return
if version != 0:
logger().error("Invalid OGG version: %u, expected %u" % (version, 0))
return
if header_type != 2: # should be first page of stream
logger().error("Invalid OGG page header type: %u, expected %u" % (header_type, 2))
return
if page_sequence_number != 0:
logger().error("Invalid OGG page sequence number: %u, expected %u" % (page_sequence_number, 0))
return
segment_table_fmt = struct.Struct("<%uB" % (page_segments))
chunk = file.read(segment_table_fmt.size)
first_ogg_page.extend(chunk)
if len(chunk) < segment_table_fmt.size:
logger().error("Not enough bytes for OGG segment table: %u, expected at least %u" % (len(chunk),
segment_table_fmt.size))
return
segment_table = segment_table_fmt.unpack(chunk)
# check crc of first page
first_ogg_page_size = OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size + sum(segment_table)
chunk = file.read(sum(segment_table))
first_ogg_page.extend(chunk)
if len(first_ogg_page) < first_ogg_page_size:
logger().error("Not enough bytes for first OGG page: %u, expected at least %u" % (len(first_ogg_page),
first_ogg_page_size))
return
computed_crc = _compute_ogg_page_crc(first_ogg_page)
if computed_crc != crc_checksum:
logger().error("Invalid OGG page CRC: 0x%08x, expected 0x%08x" % (crc_checksum, computed_crc))
return
#
# Opus header
#
chunk = first_ogg_page[OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size:][:segment_table[0]]
if len(chunk) < OGG_OPUS_ID_HEADER.size:
logger().error("Not enough bytes for Opus Identification header: %u, "
"expected at least %u" % (len(chunk),
OGG_OPUS_ID_HEADER.size))
return
magic, version, channel_count, preskip, input_samplerate, output_gain, \
mapping_family = OGG_OPUS_ID_HEADER.unpack(chunk[:OGG_OPUS_ID_HEADER.size])
if magic != b"OpusHead":
logger().error("Invalid Opus magic number: %s, expected '%s'" % (repr(magic), "OpusHead"))
return
if (version >> 4) != 0:
logger().error("Invalid Opus version: 0x%x, expected 0x0-0xf" % (version))
return
# seek to Opus header
file.seek(OGG_FIRST_PAGE_HEADER.size + segment_table_fmt.size)
return output_gain | Parse an OggOpus file headers, read and return its output gain, and set file seek position to start of Opus header. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L28-L99 |
desbma/r128gain | r128gain/opusgain.py | write_oggopus_output_gain | def write_oggopus_output_gain(file, new_output_gain):
""" Write output gain Opus header for a file.
file must be an object successfully used by parse_oggopus_output_gain.
"""
opus_header_pos = file.tell()
# write Opus header with new gain
file.seek(opus_header_pos + OGG_OPUS_ID_HEADER_GAIN_OFFSET)
file.write(OGG_OPUS_ID_HEADER_GAIN.pack(new_output_gain))
# compute page crc
file.seek(0)
page = file.read(opus_header_pos + OGG_OPUS_ID_HEADER.size)
computed_crc = _compute_ogg_page_crc(page)
# write CRC
file.seek(OGG_FIRST_PAGE_HEADER_CRC_OFFSET)
file.write(OGG_FIRST_PAGE_HEADER_CRC.pack(computed_crc)) | python | def write_oggopus_output_gain(file, new_output_gain):
""" Write output gain Opus header for a file.
file must be an object successfully used by parse_oggopus_output_gain.
"""
opus_header_pos = file.tell()
# write Opus header with new gain
file.seek(opus_header_pos + OGG_OPUS_ID_HEADER_GAIN_OFFSET)
file.write(OGG_OPUS_ID_HEADER_GAIN.pack(new_output_gain))
# compute page crc
file.seek(0)
page = file.read(opus_header_pos + OGG_OPUS_ID_HEADER.size)
computed_crc = _compute_ogg_page_crc(page)
# write CRC
file.seek(OGG_FIRST_PAGE_HEADER_CRC_OFFSET)
file.write(OGG_FIRST_PAGE_HEADER_CRC.pack(computed_crc)) | Write output gain Opus header for a file.
file must be an object successfully used by parse_oggopus_output_gain. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L102-L120 |
desbma/r128gain | r128gain/opusgain.py | _compute_ogg_page_crc | def _compute_ogg_page_crc(page):
""" Compute CRC of an Ogg page. """
page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \
b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \
page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:]
return ogg_page_crc(page_zero_crc) | python | def _compute_ogg_page_crc(page):
""" Compute CRC of an Ogg page. """
page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \
b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \
page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:]
return ogg_page_crc(page_zero_crc) | Compute CRC of an Ogg page. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/opusgain.py#L123-L128 |
desbma/r128gain | r128gain/__init__.py | get_ffmpeg_lib_versions | def get_ffmpeg_lib_versions(ffmpeg_path=None):
""" Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion.
Example: 0x3040100 for FFmpeg 3.4.1
"""
r = collections.OrderedDict()
cmd = (ffmpeg_path or "ffmpeg", "-version")
output = subprocess.run(cmd,
check=True,
stdout=subprocess.PIPE,
universal_newlines=True).stdout
output = output.splitlines()
lib_version_regex = re.compile("^\s*(lib[a-z]+)\s+([0-9]+).\s*([0-9]+).\s*([0-9]+)\s+")
for line in output:
match = lib_version_regex.search(line)
if match:
lib_name, *lib_version = match.group(1, 2, 3, 4)
int_lib_version = 0
for i, d in enumerate(map(int, reversed(lib_version)), 1):
int_lib_version |= d << (8 * i)
r[lib_name] = int_lib_version
return r | python | def get_ffmpeg_lib_versions(ffmpeg_path=None):
""" Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion.
Example: 0x3040100 for FFmpeg 3.4.1
"""
r = collections.OrderedDict()
cmd = (ffmpeg_path or "ffmpeg", "-version")
output = subprocess.run(cmd,
check=True,
stdout=subprocess.PIPE,
universal_newlines=True).stdout
output = output.splitlines()
lib_version_regex = re.compile("^\s*(lib[a-z]+)\s+([0-9]+).\s*([0-9]+).\s*([0-9]+)\s+")
for line in output:
match = lib_version_regex.search(line)
if match:
lib_name, *lib_version = match.group(1, 2, 3, 4)
int_lib_version = 0
for i, d in enumerate(map(int, reversed(lib_version)), 1):
int_lib_version |= d << (8 * i)
r[lib_name] = int_lib_version
return r | Get FFmpeg library versions as 32 bit integers, with same format as sys.hexversion.
Example: 0x3040100 for FFmpeg 3.4.1 | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L47-L68 |
desbma/r128gain | r128gain/__init__.py | format_ffmpeg_filter | def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) | python | def format_ffmpeg_filter(name, params):
""" Build a string to call a FFMpeg filter. """
return "%s=%s" % (name,
":".join("%s=%s" % (k, v) for k, v in params.items())) | Build a string to call a FFMpeg filter. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L71-L74 |
desbma/r128gain | r128gain/__init__.py | get_r128_loudness | def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None):
""" Get R128 loudness loudness level and sample peak. """
logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "",
", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths)))
# build command line
cmd = [ffmpeg_path or "ffmpeg",
"-hide_banner", "-nostats"]
for i, audio_filepath in enumerate(audio_filepaths):
if not enable_ffmpeg_threading:
cmd.extend(("-threads:%u" % (i), "1")) # single decoding thread
cmd.extend(("-i", audio_filepath))
if (get_ffmpeg_lib_versions()["libavfilter"] >= 0x06526400) and (not enable_ffmpeg_threading):
cmd.extend(("-filter_threads", "1")) # single filter thread
cmd.extend(("-map", "a"))
ebur128_filter_params = {"framelog": "verbose"}
aformat_r128_filter_params = {"sample_fmts": "s16",
"sample_rates": "48000",
"channel_layouts": "stereo"}
aformat_rg_filter_params = {"sample_fmts": "s16"}
filter_chain = []
if len(audio_filepaths) > 1:
cmd.append("-filter_complex")
for i in range(len(audio_filepaths)):
if calc_peak:
filter_chain.append("[%u:a]asplit[a_rg_in_%u][a_r128_in_%u]" % (i, i, i))
filter_chain.append("[a_rg_in_%u]%s,replaygain,anullsink" % (i,
format_ffmpeg_filter("aformat",
aformat_rg_filter_params)))
else:
filter_chain.append("[%u:a]anul[a_r128_in_%u]" % (i, i))
filter_chain.append("[a_r128_in_%u]%s,afifo[a_r128_in_fmt_%u]" % (i,
format_ffmpeg_filter("aformat",
aformat_r128_filter_params),
i))
filter_chain.append("%sconcat=n=%u:v=0:a=1[a_r128_in_concat]" % ("".join(("[a_r128_in_fmt_%u]" % (i)) for i in range(len(audio_filepaths))),
len(audio_filepaths)))
filter_chain.append("[a_r128_in_concat]%s" % (format_ffmpeg_filter("ebur128", ebur128_filter_params)))
cmd.append("; ".join(filter_chain))
else:
if calc_peak:
filter_chain.extend((format_ffmpeg_filter("aformat", aformat_rg_filter_params),
"replaygain"))
filter_chain.append(format_ffmpeg_filter("ebur128", ebur128_filter_params))
# filter_chain.append("anullsink")
cmd.extend(("-filter:a", ",".join(filter_chain)))
cmd.extend(("-f", "null", os.devnull))
# run
logger().debug(subprocess.list2cmdline(cmd))
output = subprocess.run(cmd,
check=True,
stdin=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
output = output.decode("utf-8", errors="replace").splitlines()
if calc_peak:
# parse replaygain filter output
sample_peaks = []
for line in reversed(output):
if line.startswith("[Parsed_replaygain_") and ("] track_peak = " in line):
sample_peaks.append(float(line.rsplit("=", 1)[1]))
if len(sample_peaks) == len(audio_filepaths):
break
sample_peak = max(sample_peaks)
else:
sample_peak = None
# parse r128 filter output
for i in reversed(range(len(output))):
line = output[i]
if line.startswith("[Parsed_ebur128_") and line.endswith("Summary:"):
break
output = filter(lambda x: x and not x.startswith("[Parsed_replaygain_"),
map(str.strip, output[i:]))
r128_stats = dict(tuple(map(str.strip, line.split(":", 1))) for line in output if not line.endswith(":"))
r128_stats = {k: float(v.split(" ", 1)[0]) for k, v in r128_stats.items()}
return r128_stats["I"], sample_peak | python | def get_r128_loudness(audio_filepaths, *, calc_peak=True, enable_ffmpeg_threading=True, ffmpeg_path=None):
""" Get R128 loudness loudness level and sample peak. """
logger().info("Analyzing loudness of file%s %s..." % ("s" if (len(audio_filepaths) > 1) else "",
", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths)))
# build command line
cmd = [ffmpeg_path or "ffmpeg",
"-hide_banner", "-nostats"]
for i, audio_filepath in enumerate(audio_filepaths):
if not enable_ffmpeg_threading:
cmd.extend(("-threads:%u" % (i), "1")) # single decoding thread
cmd.extend(("-i", audio_filepath))
if (get_ffmpeg_lib_versions()["libavfilter"] >= 0x06526400) and (not enable_ffmpeg_threading):
cmd.extend(("-filter_threads", "1")) # single filter thread
cmd.extend(("-map", "a"))
ebur128_filter_params = {"framelog": "verbose"}
aformat_r128_filter_params = {"sample_fmts": "s16",
"sample_rates": "48000",
"channel_layouts": "stereo"}
aformat_rg_filter_params = {"sample_fmts": "s16"}
filter_chain = []
if len(audio_filepaths) > 1:
cmd.append("-filter_complex")
for i in range(len(audio_filepaths)):
if calc_peak:
filter_chain.append("[%u:a]asplit[a_rg_in_%u][a_r128_in_%u]" % (i, i, i))
filter_chain.append("[a_rg_in_%u]%s,replaygain,anullsink" % (i,
format_ffmpeg_filter("aformat",
aformat_rg_filter_params)))
else:
filter_chain.append("[%u:a]anul[a_r128_in_%u]" % (i, i))
filter_chain.append("[a_r128_in_%u]%s,afifo[a_r128_in_fmt_%u]" % (i,
format_ffmpeg_filter("aformat",
aformat_r128_filter_params),
i))
filter_chain.append("%sconcat=n=%u:v=0:a=1[a_r128_in_concat]" % ("".join(("[a_r128_in_fmt_%u]" % (i)) for i in range(len(audio_filepaths))),
len(audio_filepaths)))
filter_chain.append("[a_r128_in_concat]%s" % (format_ffmpeg_filter("ebur128", ebur128_filter_params)))
cmd.append("; ".join(filter_chain))
else:
if calc_peak:
filter_chain.extend((format_ffmpeg_filter("aformat", aformat_rg_filter_params),
"replaygain"))
filter_chain.append(format_ffmpeg_filter("ebur128", ebur128_filter_params))
# filter_chain.append("anullsink")
cmd.extend(("-filter:a", ",".join(filter_chain)))
cmd.extend(("-f", "null", os.devnull))
# run
logger().debug(subprocess.list2cmdline(cmd))
output = subprocess.run(cmd,
check=True,
stdin=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
output = output.decode("utf-8", errors="replace").splitlines()
if calc_peak:
# parse replaygain filter output
sample_peaks = []
for line in reversed(output):
if line.startswith("[Parsed_replaygain_") and ("] track_peak = " in line):
sample_peaks.append(float(line.rsplit("=", 1)[1]))
if len(sample_peaks) == len(audio_filepaths):
break
sample_peak = max(sample_peaks)
else:
sample_peak = None
# parse r128 filter output
for i in reversed(range(len(output))):
line = output[i]
if line.startswith("[Parsed_ebur128_") and line.endswith("Summary:"):
break
output = filter(lambda x: x and not x.startswith("[Parsed_replaygain_"),
map(str.strip, output[i:]))
r128_stats = dict(tuple(map(str.strip, line.split(":", 1))) for line in output if not line.endswith(":"))
r128_stats = {k: float(v.split(" ", 1)[0]) for k, v in r128_stats.items()}
return r128_stats["I"], sample_peak | Get R128 loudness loudness level and sample peak. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L77-L155 |
desbma/r128gain | r128gain/__init__.py | scan | def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None):
""" Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. """
r128_data = {}
with contextlib.ExitStack() as cm:
if executor is None:
if thread_count is None:
try:
thread_count = len(os.sched_getaffinity(0))
except AttributeError:
thread_count = os.cpu_count()
enable_ffmpeg_threading = thread_count > (len(audio_filepaths) + int(album_gain))
executor = cm.enter_context(concurrent.futures.ThreadPoolExecutor(max_workers=thread_count))
asynchronous = False
else:
enable_ffmpeg_threading = False
asynchronous = True
loudness_tags = tuple(map(has_loudness_tag, audio_filepaths))
# remove invalid files
audio_filepaths = tuple(audio_filepath for (audio_filepath,
has_tags) in zip(audio_filepaths,
loudness_tags) if has_tags is not None)
loudness_tags = tuple(filter(None, loudness_tags))
futures = {}
if album_gain:
if skip_tagged and all(map(operator.itemgetter(1), loudness_tags)):
logger().info("All files already have an album gain tag, skipping album gain scan")
elif audio_filepaths:
calc_album_peak = any(map(lambda x: os.path.splitext(x)[-1].lower() != ".opus",
audio_filepaths))
futures[ALBUM_GAIN_KEY] = executor.submit(get_r128_loudness,
audio_filepaths,
calc_peak=calc_album_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
for audio_filepath in audio_filepaths:
if skip_tagged and has_loudness_tag(audio_filepath)[0]:
logger().info("File '%s' already has a track gain tag, skipping track gain scan" % (audio_filepath))
continue
if os.path.splitext(audio_filepath)[-1].lower() == ".opus":
# http://www.rfcreader.com/#rfc7845_line1060
calc_peak = False
else:
calc_peak = True
futures[audio_filepath] = executor.submit(get_r128_loudness,
(audio_filepath,),
calc_peak=calc_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
if asynchronous:
return futures
for audio_filepath in audio_filepaths:
try:
r128_data[audio_filepath] = futures[audio_filepath].result()
except KeyError:
# track gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze file '%s': %s %s" % (audio_filepath,
e.__class__.__qualname__,
e))
if album_gain and audio_filepaths:
try:
r128_data[ALBUM_GAIN_KEY] = futures[ALBUM_GAIN_KEY].result()
except KeyError:
# album gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze files %s: %s %s" % (", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths),
e.__class__.__qualname__,
e))
return r128_data | python | def scan(audio_filepaths, *, album_gain=False, skip_tagged=False, thread_count=None, ffmpeg_path=None, executor=None):
""" Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. """
r128_data = {}
with contextlib.ExitStack() as cm:
if executor is None:
if thread_count is None:
try:
thread_count = len(os.sched_getaffinity(0))
except AttributeError:
thread_count = os.cpu_count()
enable_ffmpeg_threading = thread_count > (len(audio_filepaths) + int(album_gain))
executor = cm.enter_context(concurrent.futures.ThreadPoolExecutor(max_workers=thread_count))
asynchronous = False
else:
enable_ffmpeg_threading = False
asynchronous = True
loudness_tags = tuple(map(has_loudness_tag, audio_filepaths))
# remove invalid files
audio_filepaths = tuple(audio_filepath for (audio_filepath,
has_tags) in zip(audio_filepaths,
loudness_tags) if has_tags is not None)
loudness_tags = tuple(filter(None, loudness_tags))
futures = {}
if album_gain:
if skip_tagged and all(map(operator.itemgetter(1), loudness_tags)):
logger().info("All files already have an album gain tag, skipping album gain scan")
elif audio_filepaths:
calc_album_peak = any(map(lambda x: os.path.splitext(x)[-1].lower() != ".opus",
audio_filepaths))
futures[ALBUM_GAIN_KEY] = executor.submit(get_r128_loudness,
audio_filepaths,
calc_peak=calc_album_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
for audio_filepath in audio_filepaths:
if skip_tagged and has_loudness_tag(audio_filepath)[0]:
logger().info("File '%s' already has a track gain tag, skipping track gain scan" % (audio_filepath))
continue
if os.path.splitext(audio_filepath)[-1].lower() == ".opus":
# http://www.rfcreader.com/#rfc7845_line1060
calc_peak = False
else:
calc_peak = True
futures[audio_filepath] = executor.submit(get_r128_loudness,
(audio_filepath,),
calc_peak=calc_peak,
enable_ffmpeg_threading=enable_ffmpeg_threading,
ffmpeg_path=ffmpeg_path)
if asynchronous:
return futures
for audio_filepath in audio_filepaths:
try:
r128_data[audio_filepath] = futures[audio_filepath].result()
except KeyError:
# track gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze file '%s': %s %s" % (audio_filepath,
e.__class__.__qualname__,
e))
if album_gain and audio_filepaths:
try:
r128_data[ALBUM_GAIN_KEY] = futures[ALBUM_GAIN_KEY].result()
except KeyError:
# album gain was skipped
pass
except Exception as e:
# raise
logger().warning("Failed to analyze files %s: %s %s" % (", ".join("'%s'" % (audio_filepath) for audio_filepath in audio_filepaths),
e.__class__.__qualname__,
e))
return r128_data | Analyze files, and return a dictionary of filepath to loudness metadata or filepath to future if executor is not None. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L158-L236 |
desbma/r128gain | r128gain/__init__.py | tag | def tag(filepath, loudness, peak, *,
album_loudness=None, album_peak=None, opus_output_gain=False, mtime_second_offset=None):
""" Tag audio file with loudness metadata. """
assert((loudness is not None) or (album_loudness is not None))
if peak is not None:
assert(0 <= peak <= 1.0)
if album_peak is not None:
assert(0 <= album_peak <= 1.0)
logger().info("Tagging file '%s'" % (filepath))
original_mtime = os.path.getmtime(filepath)
mf = mutagen.File(filepath)
if (mf is not None) and (mf.tags is None):
mf.add_tags()
if (isinstance(mf.tags, mutagen.id3.ID3) or
isinstance(mf, mutagen.id3.ID3FileType)):
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification#ID3v2
if loudness is not None:
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_TRACK_GAIN",
text="%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)))
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_TRACK_PEAK",
text="%.6f" % (peak)))
if album_loudness is not None:
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_ALBUM_GAIN",
text="%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)))
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_ALBUM_PEAK",
text="%.6f" % (album_peak)))
# other legacy formats:
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_legacy_metadata_formats#ID3v2_RGAD
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_legacy_metadata_formats#ID3v2_RVA2
elif isinstance(mf, mutagen.oggopus.OggOpus):
if opus_output_gain and (loudness is not None):
with open(filepath, "r+b") as file:
current_output_gain = opusgain.parse_oggopus_output_gain(file)
new_output_gain = current_output_gain + float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - loudness)
opusgain.write_oggopus_output_gain(file, new_output_gain)
# now that the output gain header is written, we will write the R128 tag for the new loudness
loudness = OPUS_REF_R128_LOUDNESS_DBFS
if album_loudness is not None:
# assume the whole album will be normalized the same way
# TODO better behavior? rescan album? disable R128 tags?
album_loudness = OPUS_REF_R128_LOUDNESS_DBFS
# https://wiki.xiph.org/OggOpus#Comment_Header
if loudness is not None:
q78 = float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - loudness)
assert(-32768 <= q78 <= 32767)
mf["R128_TRACK_GAIN"] = str(q78)
if album_loudness is not None:
q78 = float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - album_loudness)
assert(-32768 <= q78 <= 32767)
mf["R128_ALBUM_GAIN"] = str(q78)
elif (isinstance(mf.tags, (mutagen._vorbis.VComment, mutagen.apev2.APEv2)) or
isinstance(mf, (mutagen.ogg.OggFileType, mutagen.apev2.APEv2File))):
# https://wiki.xiph.org/VorbisComment#Replay_Gain
if loudness is not None:
mf["REPLAYGAIN_TRACK_GAIN"] = "%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)
mf["REPLAYGAIN_TRACK_PEAK"] = "%.8f" % (peak)
if album_loudness is not None:
mf["REPLAYGAIN_ALBUM_GAIN"] = "%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)
mf["REPLAYGAIN_ALBUM_PEAK"] = "%.8f" % (album_peak)
elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
isinstance(mf, mutagen.mp4.MP4)):
# https://github.com/xbmc/xbmc/blob/9e855967380ef3a5d25718ff2e6db5e3dd2e2829/xbmc/music/tags/TagLoaderTagLib.cpp#L806-L812
if loudness is not None:
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"] = mutagen.mp4.MP4FreeForm(("%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)).encode())
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_PEAK"] = mutagen.mp4.MP4FreeForm(("%.6f" % (peak)).encode())
if album_loudness is not None:
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"] = mutagen.mp4.MP4FreeForm(("%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)).encode())
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_PEAK"] = mutagen.mp4.MP4FreeForm(("%.6f" % (album_peak)).encode())
else:
logger().warning("Unhandled '%s' tag format for file '%s'" % (mf.__class__.__name__,
filepath))
return
mf.save()
# preserve original modification time, possibly increasing it by some seconds
if mtime_second_offset is not None:
if mtime_second_offset == 0:
logger().debug("Restoring modification time for file '{}'".format(filepath))
else:
logger().debug("Restoring modification time for file '{}' (adding {} seconds)".format(filepath,
mtime_second_offset))
os.utime(filepath, times=(os.stat(filepath).st_atime, original_mtime + mtime_second_offset)) | python | def tag(filepath, loudness, peak, *,
album_loudness=None, album_peak=None, opus_output_gain=False, mtime_second_offset=None):
""" Tag audio file with loudness metadata. """
assert((loudness is not None) or (album_loudness is not None))
if peak is not None:
assert(0 <= peak <= 1.0)
if album_peak is not None:
assert(0 <= album_peak <= 1.0)
logger().info("Tagging file '%s'" % (filepath))
original_mtime = os.path.getmtime(filepath)
mf = mutagen.File(filepath)
if (mf is not None) and (mf.tags is None):
mf.add_tags()
if (isinstance(mf.tags, mutagen.id3.ID3) or
isinstance(mf, mutagen.id3.ID3FileType)):
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_2.0_specification#ID3v2
if loudness is not None:
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_TRACK_GAIN",
text="%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)))
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_TRACK_PEAK",
text="%.6f" % (peak)))
if album_loudness is not None:
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_ALBUM_GAIN",
text="%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)))
mf.tags.add(mutagen.id3.TXXX(encoding=mutagen.id3.Encoding.LATIN1,
desc="REPLAYGAIN_ALBUM_PEAK",
text="%.6f" % (album_peak)))
# other legacy formats:
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_legacy_metadata_formats#ID3v2_RGAD
# http://wiki.hydrogenaud.io/index.php?title=ReplayGain_legacy_metadata_formats#ID3v2_RVA2
elif isinstance(mf, mutagen.oggopus.OggOpus):
if opus_output_gain and (loudness is not None):
with open(filepath, "r+b") as file:
current_output_gain = opusgain.parse_oggopus_output_gain(file)
new_output_gain = current_output_gain + float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - loudness)
opusgain.write_oggopus_output_gain(file, new_output_gain)
# now that the output gain header is written, we will write the R128 tag for the new loudness
loudness = OPUS_REF_R128_LOUDNESS_DBFS
if album_loudness is not None:
# assume the whole album will be normalized the same way
# TODO better behavior? rescan album? disable R128 tags?
album_loudness = OPUS_REF_R128_LOUDNESS_DBFS
# https://wiki.xiph.org/OggOpus#Comment_Header
if loudness is not None:
q78 = float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - loudness)
assert(-32768 <= q78 <= 32767)
mf["R128_TRACK_GAIN"] = str(q78)
if album_loudness is not None:
q78 = float_to_q7dot8(OPUS_REF_R128_LOUDNESS_DBFS - album_loudness)
assert(-32768 <= q78 <= 32767)
mf["R128_ALBUM_GAIN"] = str(q78)
elif (isinstance(mf.tags, (mutagen._vorbis.VComment, mutagen.apev2.APEv2)) or
isinstance(mf, (mutagen.ogg.OggFileType, mutagen.apev2.APEv2File))):
# https://wiki.xiph.org/VorbisComment#Replay_Gain
if loudness is not None:
mf["REPLAYGAIN_TRACK_GAIN"] = "%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)
mf["REPLAYGAIN_TRACK_PEAK"] = "%.8f" % (peak)
if album_loudness is not None:
mf["REPLAYGAIN_ALBUM_GAIN"] = "%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)
mf["REPLAYGAIN_ALBUM_PEAK"] = "%.8f" % (album_peak)
elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
isinstance(mf, mutagen.mp4.MP4)):
# https://github.com/xbmc/xbmc/blob/9e855967380ef3a5d25718ff2e6db5e3dd2e2829/xbmc/music/tags/TagLoaderTagLib.cpp#L806-L812
if loudness is not None:
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"] = mutagen.mp4.MP4FreeForm(("%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - loudness)).encode())
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_PEAK"] = mutagen.mp4.MP4FreeForm(("%.6f" % (peak)).encode())
if album_loudness is not None:
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"] = mutagen.mp4.MP4FreeForm(("%.2f dB" % (RG2_REF_R128_LOUDNESS_DBFS - album_loudness)).encode())
mf["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_PEAK"] = mutagen.mp4.MP4FreeForm(("%.6f" % (album_peak)).encode())
else:
logger().warning("Unhandled '%s' tag format for file '%s'" % (mf.__class__.__name__,
filepath))
return
mf.save()
# preserve original modification time, possibly increasing it by some seconds
if mtime_second_offset is not None:
if mtime_second_offset == 0:
logger().debug("Restoring modification time for file '{}'".format(filepath))
else:
logger().debug("Restoring modification time for file '{}' (adding {} seconds)".format(filepath,
mtime_second_offset))
os.utime(filepath, times=(os.stat(filepath).st_atime, original_mtime + mtime_second_offset)) | Tag audio file with loudness metadata. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L257-L352 |
desbma/r128gain | r128gain/__init__.py | has_loudness_tag | def has_loudness_tag(filepath):
""" Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid. """
track, album = False, False
try:
mf = mutagen.File(filepath)
except mutagen.MutagenError as e:
logger().warning("File '%s' %s: %s" % (filepath,
e.__class__.__qualname__,
e))
return
if (isinstance(mf.tags, mutagen.id3.ID3) or
isinstance(mf, mutagen.id3.ID3FileType)):
track = ("TXXX:REPLAYGAIN_TRACK_GAIN" in mf) and ("TXXX:REPLAYGAIN_TRACK_PEAK" in mf)
album = ("TXXX:REPLAYGAIN_ALBUM_GAIN" in mf) and ("TXXX:REPLAYGAIN_ALBUM_PEAK" in mf)
elif isinstance(mf, mutagen.oggopus.OggOpus):
track = "R128_TRACK_GAIN" in mf
album = "R128_ALBUM_GAIN" in mf
elif (isinstance(mf.tags, (mutagen._vorbis.VComment, mutagen.apev2.APEv2)) or
isinstance(mf, (mutagen.ogg.OggFileType, mutagen.apev2.APEv2File))):
track = ("REPLAYGAIN_TRACK_GAIN" in mf) and ("REPLAYGAIN_TRACK_PEAK" in mf)
album = ("REPLAYGAIN_ALBUM_GAIN" in mf) and ("REPLAYGAIN_ALBUM_PEAK" in mf)
elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
isinstance(mf, mutagen.mp4.MP4)):
track = ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_PEAK" in mf)
album = ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_PEAK" in mf)
else:
logger().warning("Unhandled '%s' tag format for file '%s'" % (mf.__class__.__name__,
filepath))
return
return track, album | python | def has_loudness_tag(filepath):
""" Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid. """
track, album = False, False
try:
mf = mutagen.File(filepath)
except mutagen.MutagenError as e:
logger().warning("File '%s' %s: %s" % (filepath,
e.__class__.__qualname__,
e))
return
if (isinstance(mf.tags, mutagen.id3.ID3) or
isinstance(mf, mutagen.id3.ID3FileType)):
track = ("TXXX:REPLAYGAIN_TRACK_GAIN" in mf) and ("TXXX:REPLAYGAIN_TRACK_PEAK" in mf)
album = ("TXXX:REPLAYGAIN_ALBUM_GAIN" in mf) and ("TXXX:REPLAYGAIN_ALBUM_PEAK" in mf)
elif isinstance(mf, mutagen.oggopus.OggOpus):
track = "R128_TRACK_GAIN" in mf
album = "R128_ALBUM_GAIN" in mf
elif (isinstance(mf.tags, (mutagen._vorbis.VComment, mutagen.apev2.APEv2)) or
isinstance(mf, (mutagen.ogg.OggFileType, mutagen.apev2.APEv2File))):
track = ("REPLAYGAIN_TRACK_GAIN" in mf) and ("REPLAYGAIN_TRACK_PEAK" in mf)
album = ("REPLAYGAIN_ALBUM_GAIN" in mf) and ("REPLAYGAIN_ALBUM_PEAK" in mf)
elif (isinstance(mf.tags, mutagen.mp4.MP4Tags) or
isinstance(mf, mutagen.mp4.MP4)):
track = ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_PEAK" in mf)
album = ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN" in mf) and ("----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_PEAK" in mf)
else:
logger().warning("Unhandled '%s' tag format for file '%s'" % (mf.__class__.__name__,
filepath))
return
return track, album | Return a pair of booleans indicating if filepath has a RG or R128 track/album tag, or None if file is invalid. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L355-L391 |
desbma/r128gain | r128gain/__init__.py | show_scan_report | def show_scan_report(audio_filepaths, album_dir, r128_data):
""" Display loudness scan results. """
# track loudness/peak
for audio_filepath in audio_filepaths:
try:
loudness, peak = r128_data[audio_filepath]
except KeyError:
loudness, peak = "SKIPPED", "SKIPPED"
else:
loudness = "%.1f LUFS" % (loudness)
if peak is None:
peak = "-"
else:
peak = "%.1f dBFS" % (scale_to_gain(peak))
logger().info("File '%s': loudness = %s, sample peak = %s" % (audio_filepath, loudness, peak))
# album loudness/peak
if album_dir:
try:
album_loudness, album_peak = r128_data[ALBUM_GAIN_KEY]
except KeyError:
album_loudness, album_peak = "SKIPPED", "SKIPPED"
else:
album_loudness = "%.1f LUFS" % (album_loudness)
if album_peak is None:
album_peak = "-"
else:
album_peak = "%.1f dBFS" % (scale_to_gain(album_peak))
logger().info("Album '%s': loudness = %s, sample peak = %s" % (album_dir, album_loudness, album_peak)) | python | def show_scan_report(audio_filepaths, album_dir, r128_data):
""" Display loudness scan results. """
# track loudness/peak
for audio_filepath in audio_filepaths:
try:
loudness, peak = r128_data[audio_filepath]
except KeyError:
loudness, peak = "SKIPPED", "SKIPPED"
else:
loudness = "%.1f LUFS" % (loudness)
if peak is None:
peak = "-"
else:
peak = "%.1f dBFS" % (scale_to_gain(peak))
logger().info("File '%s': loudness = %s, sample peak = %s" % (audio_filepath, loudness, peak))
# album loudness/peak
if album_dir:
try:
album_loudness, album_peak = r128_data[ALBUM_GAIN_KEY]
except KeyError:
album_loudness, album_peak = "SKIPPED", "SKIPPED"
else:
album_loudness = "%.1f LUFS" % (album_loudness)
if album_peak is None:
album_peak = "-"
else:
album_peak = "%.1f dBFS" % (scale_to_gain(album_peak))
logger().info("Album '%s': loudness = %s, sample peak = %s" % (album_dir, album_loudness, album_peak)) | Display loudness scan results. | https://github.com/desbma/r128gain/blob/011ee26fe3705a50925571785d206cba2806089a/r128gain/__init__.py#L394-L422 |
clemfromspace/scrapy-cloudflare-middleware | setup.py | get_requirements | def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
install_reqs = parse_requirements(filename=source, session=PipSession())
return [str(ir.req) for ir in install_reqs] | python | def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
install_reqs = parse_requirements(filename=source, session=PipSession())
return [str(ir.req) for ir in install_reqs] | Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/setup.py#L8-L20 |
clemfromspace/scrapy-cloudflare-middleware | scrapy_cloudflare_middleware/middlewares.py | CloudFlareMiddleware.is_cloudflare_challenge | def is_cloudflare_challenge(response):
"""Test if the given response contains the cloudflare's anti-bot protection"""
return (
response.status == 503
and response.headers.get('Server', '').startswith(b'cloudflare')
and 'jschl_vc' in response.text
and 'jschl_answer' in response.text
) | python | def is_cloudflare_challenge(response):
"""Test if the given response contains the cloudflare's anti-bot protection"""
return (
response.status == 503
and response.headers.get('Server', '').startswith(b'cloudflare')
and 'jschl_vc' in response.text
and 'jschl_answer' in response.text
) | Test if the given response contains the cloudflare's anti-bot protection | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L12-L20 |
clemfromspace/scrapy-cloudflare-middleware | scrapy_cloudflare_middleware/middlewares.py | CloudFlareMiddleware.process_response | def process_response(self, request, response, spider):
"""Handle the a Scrapy response"""
if not self.is_cloudflare_challenge(response):
return response
logger = logging.getLogger('cloudflaremiddleware')
logger.debug(
'Cloudflare protection detected on %s, trying to bypass...',
response.url
)
cloudflare_tokens, __ = get_tokens(
request.url,
user_agent=spider.settings.get('USER_AGENT')
)
logger.debug(
'Successfully bypassed the protection for %s, re-scheduling the request',
response.url
)
request.cookies.update(cloudflare_tokens)
request.priority = 99999
return request | python | def process_response(self, request, response, spider):
"""Handle the a Scrapy response"""
if not self.is_cloudflare_challenge(response):
return response
logger = logging.getLogger('cloudflaremiddleware')
logger.debug(
'Cloudflare protection detected on %s, trying to bypass...',
response.url
)
cloudflare_tokens, __ = get_tokens(
request.url,
user_agent=spider.settings.get('USER_AGENT')
)
logger.debug(
'Successfully bypassed the protection for %s, re-scheduling the request',
response.url
)
request.cookies.update(cloudflare_tokens)
request.priority = 99999
return request | Handle the a Scrapy response | https://github.com/clemfromspace/scrapy-cloudflare-middleware/blob/03ccea9164418dabe8180053165b0da0bffa0741/scrapy_cloudflare_middleware/middlewares.py#L22-L48 |
Fahreeve/aiovk | aiovk/sessions.py | TokenSession.enter_captcha | async def enter_captcha(self, url: str, sid: str) -> str:
"""
Override this method for processing captcha.
:param url: link to captcha image
:param sid: captcha id. I do not know why pass here but may be useful
:return captcha value
"""
raise VkCaptchaNeeded(url, sid) | python | async def enter_captcha(self, url: str, sid: str) -> str:
"""
Override this method for processing captcha.
:param url: link to captcha image
:param sid: captcha id. I do not know why pass here but may be useful
:return captcha value
"""
raise VkCaptchaNeeded(url, sid) | Override this method for processing captcha.
:param url: link to captcha image
:param sid: captcha id. I do not know why pass here but may be useful
:return captcha value | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L104-L112 |
Fahreeve/aiovk | aiovk/sessions.py | ImplicitSession.authorize | async def authorize(self) -> None:
"""Getting a new token from server"""
html = await self._get_auth_page()
url = URL('/authorize?email')
for step in range(self.num_of_attempts):
if url.path == '/authorize' and 'email' in url.query:
# Invalid login or password and 'email' in q.query
url, html = await self._process_auth_form(html)
if url.path == '/login' and url.query.get('act', '') == 'authcheck':
# Entering 2auth code
url, html = await self._process_2auth_form(html)
if url.path == '/login' and url.query.get('act', '') == 'authcheck_code':
# Need captcha
url, html = await self._process_auth_form(html)
if url.path == '/authorize' and '__q_hash' in url.query:
# Give rights for app
url, html = await self._process_access_form(html)
if url.path == '/blank.html':
# Success
self.access_token = url.query['access_token']
return
raise VkAuthError('Something went wrong', 'Exceeded the number of attempts to log in') | python | async def authorize(self) -> None:
"""Getting a new token from server"""
html = await self._get_auth_page()
url = URL('/authorize?email')
for step in range(self.num_of_attempts):
if url.path == '/authorize' and 'email' in url.query:
# Invalid login or password and 'email' in q.query
url, html = await self._process_auth_form(html)
if url.path == '/login' and url.query.get('act', '') == 'authcheck':
# Entering 2auth code
url, html = await self._process_2auth_form(html)
if url.path == '/login' and url.query.get('act', '') == 'authcheck_code':
# Need captcha
url, html = await self._process_auth_form(html)
if url.path == '/authorize' and '__q_hash' in url.query:
# Give rights for app
url, html = await self._process_access_form(html)
if url.path == '/blank.html':
# Success
self.access_token = url.query['access_token']
return
raise VkAuthError('Something went wrong', 'Exceeded the number of attempts to log in') | Getting a new token from server | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L143-L164 |
Fahreeve/aiovk | aiovk/sessions.py | ImplicitSession._get_auth_page | async def _get_auth_page(self) -> str:
"""
Get authorization mobile page without js
:return: html page
"""
# Prepare request
params = {
'client_id': self.app_id,
'redirect_uri': 'https://oauth.vk.com/blank.html',
'display': 'mobile',
'response_type': 'token',
'v': self.API_VERSION
}
if self.scope:
params['scope'] = self.scope
# Send request
status, response = await self.driver.get_text(self.AUTH_URL, params)
# Process response
if status != 200:
error_dict = json.loads(response)
raise VkAuthError(error_dict['error'], error_dict['error_description'], self.AUTH_URL, params)
return response | python | async def _get_auth_page(self) -> str:
"""
Get authorization mobile page without js
:return: html page
"""
# Prepare request
params = {
'client_id': self.app_id,
'redirect_uri': 'https://oauth.vk.com/blank.html',
'display': 'mobile',
'response_type': 'token',
'v': self.API_VERSION
}
if self.scope:
params['scope'] = self.scope
# Send request
status, response = await self.driver.get_text(self.AUTH_URL, params)
# Process response
if status != 200:
error_dict = json.loads(response)
raise VkAuthError(error_dict['error'], error_dict['error_description'], self.AUTH_URL, params)
return response | Get authorization mobile page without js
:return: html page | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L166-L189 |
Fahreeve/aiovk | aiovk/sessions.py | ImplicitSession._process_auth_form | async def _process_auth_form(self, html: str) -> (str, str):
"""
Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AuthPageParser()
p.feed(html)
p.close()
# Get data from hidden inputs
form_data = dict(p.inputs)
form_url = p.url
form_data['email'] = self.login
form_data['pass'] = self.password
if p.message:
# Show form errors
raise VkAuthError('invalid_data', p.message, form_url, form_data)
elif p.captcha_url:
form_data['captcha_key'] = await self.enter_captcha(
"https://m.vk.com{}".format(p.captcha_url),
form_data['captcha_sid']
)
form_url = "https://m.vk.com{}".format(form_url)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_auth_form(self, html: str) -> (str, str):
"""
Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AuthPageParser()
p.feed(html)
p.close()
# Get data from hidden inputs
form_data = dict(p.inputs)
form_url = p.url
form_data['email'] = self.login
form_data['pass'] = self.password
if p.message:
# Show form errors
raise VkAuthError('invalid_data', p.message, form_url, form_data)
elif p.captcha_url:
form_data['captcha_key'] = await self.enter_captcha(
"https://m.vk.com{}".format(p.captcha_url),
form_data['captcha_sid']
)
form_url = "https://m.vk.com{}".format(form_url)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | Parsing data from authorization page and filling the form and submitting the form
:param html: html page
:return: url and html from redirected page | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L191-L220 |
Fahreeve/aiovk | aiovk/sessions.py | ImplicitSession._process_2auth_form | async def _process_2auth_form(self, html: str) -> (str, str):
"""
Parsing two-factor authorization page and filling the code
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = TwoFactorCodePageParser()
p.feed(html)
p.close()
# Prepare request data
form_url = p.url
form_data = dict(p.inputs)
form_data['remember'] = 0
if p.message:
raise VkAuthError('invalid_data', p.message, form_url, form_data)
form_data['code'] = await self.enter_confirmation_code()
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_2auth_form(self, html: str) -> (str, str):
"""
Parsing two-factor authorization page and filling the code
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = TwoFactorCodePageParser()
p.feed(html)
p.close()
# Prepare request data
form_url = p.url
form_data = dict(p.inputs)
form_data['remember'] = 0
if p.message:
raise VkAuthError('invalid_data', p.message, form_url, form_data)
form_data['code'] = await self.enter_confirmation_code()
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | Parsing two-factor authorization page and filling the code
:param html: html page
:return: url and html from redirected page | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L222-L244 |
Fahreeve/aiovk | aiovk/sessions.py | ImplicitSession._process_access_form | async def _process_access_form(self, html: str) -> (str, str):
"""
Parsing page with access rights
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AccessPageParser()
p.feed(html)
p.close()
form_url = p.url
form_data = dict(p.inputs)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | python | async def _process_access_form(self, html: str) -> (str, str):
"""
Parsing page with access rights
:param html: html page
:return: url and html from redirected page
"""
# Parse page
p = AccessPageParser()
p.feed(html)
p.close()
form_url = p.url
form_data = dict(p.inputs)
# Send request
url, html = await self.driver.post_text(form_url, form_data)
return url, html | Parsing page with access rights
:param html: html page
:return: url and html from redirected page | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L246-L263 |
Fahreeve/aiovk | aiovk/sessions.py | AuthorizationCodeSession.authorize | async def authorize(self, code: str=None) -> None:
"""Getting a new token from server"""
code = await self.get_code(code)
params = {
'client_id': self.app_id,
'client_secret': self.app_secret,
'redirect_uri': self.redirect_uri,
'code': code
}
response = await self.driver.json(self.CODE_URL, params, self.timeout)
if 'error' in response:
raise VkAuthError(response['error'], response['error_description'], self.CODE_URL, params)
self.access_token = response['access_token'] | python | async def authorize(self, code: str=None) -> None:
"""Getting a new token from server"""
code = await self.get_code(code)
params = {
'client_id': self.app_id,
'client_secret': self.app_secret,
'redirect_uri': self.redirect_uri,
'code': code
}
response = await self.driver.json(self.CODE_URL, params, self.timeout)
if 'error' in response:
raise VkAuthError(response['error'], response['error_description'], self.CODE_URL, params)
self.access_token = response['access_token'] | Getting a new token from server | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/sessions.py#L295-L307 |
Fahreeve/aiovk | aiovk/longpoll.py | BaseLongPoll.wait | async def wait(self, need_pts=False) -> dict:
"""Send long poll request
:param need_pts: need return the pts field
"""
if not self.base_url:
await self._get_long_poll_server(need_pts)
params = {
'ts': self.ts,
'key': self.key,
}
params.update(self.base_params)
# invalid mimetype from server
code, response = await self.api._session.driver.get_text(
self.base_url, params,
timeout=2 * self.base_params['wait']
)
if code == 403:
raise VkLongPollError(403, 'smth weth wrong', self.base_url + '/', params)
response = json.loads(response)
failed = response.get('failed')
if not failed:
self.ts = response['ts']
return response
if failed == 1:
self.ts = response['ts']
elif failed == 4:
raise VkLongPollError(
4,
'An invalid version number was passed in the version parameter',
self.base_url + '/',
params
)
else:
self.base_url = None
return await self.wait() | python | async def wait(self, need_pts=False) -> dict:
"""Send long poll request
:param need_pts: need return the pts field
"""
if not self.base_url:
await self._get_long_poll_server(need_pts)
params = {
'ts': self.ts,
'key': self.key,
}
params.update(self.base_params)
# invalid mimetype from server
code, response = await self.api._session.driver.get_text(
self.base_url, params,
timeout=2 * self.base_params['wait']
)
if code == 403:
raise VkLongPollError(403, 'smth weth wrong', self.base_url + '/', params)
response = json.loads(response)
failed = response.get('failed')
if not failed:
self.ts = response['ts']
return response
if failed == 1:
self.ts = response['ts']
elif failed == 4:
raise VkLongPollError(
4,
'An invalid version number was passed in the version parameter',
self.base_url + '/',
params
)
else:
self.base_url = None
return await self.wait() | Send long poll request
:param need_pts: need return the pts field | https://github.com/Fahreeve/aiovk/blob/d454649d647d524c6753ba1d6ee16613355ec106/aiovk/longpoll.py#L48-L89 |
ericsuh/dirichlet | dirichlet/dirichlet.py | pdf | def pdf(alphas):
'''Returns a Dirichlet PDF function'''
alphap = alphas - 1
c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum())
def dirichlet(xs):
'''N x K array'''
return c * (xs**alphap).prod(axis=1)
return dirichlet | python | def pdf(alphas):
'''Returns a Dirichlet PDF function'''
alphap = alphas - 1
c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum())
def dirichlet(xs):
'''N x K array'''
return c * (xs**alphap).prod(axis=1)
return dirichlet | Returns a Dirichlet PDF function | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L95-L102 |
ericsuh/dirichlet | dirichlet/dirichlet.py | meanprecision | def meanprecision(a):
'''Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or concentration parameter of the Dirichlet distribution.'''
s = a.sum()
m = a / s
return (m,s) | python | def meanprecision(a):
'''Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or concentration parameter of the Dirichlet distribution.'''
s = a.sum()
m = a / s
return (m,s) | Mean and precision of Dirichlet distribution.
Parameters
----------
a : array
Parameters of Dirichlet distribution.
Returns
-------
mean : array
Numbers [0,1] of the means of the Dirichlet distribution.
precision : float
Precision or concentration parameter of the Dirichlet distribution. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L104-L121 |
ericsuh/dirichlet | dirichlet/dirichlet.py | loglikelihood | def loglikelihood(D, a):
'''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a).
Parameters
----------
D : 2D array
where ``N`` is the number of observations, ``K`` is the number of
parameters for the Dirichlet distribution.
a : array
Parameters for the Dirichlet distribution.
Returns
-------
logl : float
The log likelihood of the Dirichlet distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
return N*(gammaln(a.sum()) - gammaln(a).sum() + ((a - 1)*logp).sum()) | python | def loglikelihood(D, a):
'''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a).
Parameters
----------
D : 2D array
where ``N`` is the number of observations, ``K`` is the number of
parameters for the Dirichlet distribution.
a : array
Parameters for the Dirichlet distribution.
Returns
-------
logl : float
The log likelihood of the Dirichlet distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
return N*(gammaln(a.sum()) - gammaln(a).sum() + ((a - 1)*logp).sum()) | Compute log likelihood of Dirichlet distribution, i.e. log p(D|a).
Parameters
----------
D : 2D array
where ``N`` is the number of observations, ``K`` is the number of
parameters for the Dirichlet distribution.
a : array
Parameters for the Dirichlet distribution.
Returns
-------
logl : float
The log likelihood of the Dirichlet distribution | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L123-L140 |
ericsuh/dirichlet | dirichlet/dirichlet.py | mle | def mle(D, tol=1e-7, method='meanprecision', maxiter=None):
'''Iteratively computes maximum likelihood Dirichlet distribution
for an observed data set, i.e. a for which log p(D|a) is maximum.
Parameters
----------
D : 2D array
``N x K`` array of numbers from [0,1] where ``N`` is the number of
observations, ``K`` is the number of parameters for the Dirichlet
distribution.
tol : float
If Euclidean distance between successive parameter arrays is less than
``tol``, calculation is taken to have converged.
method : string
One of ``'fixedpoint'`` and ``'meanprecision'``, designates method by
which to find MLE Dirichlet distribution. Default is
``'meanprecision'``, which is faster.
maxiter : int
Maximum number of iterations to take calculations. Default is
``sys.maxint``.
Returns
-------
a : array
Maximum likelihood parameters for Dirichlet distribution.'''
if method == 'meanprecision':
return _meanprecision(D, tol=tol, maxiter=maxiter)
else:
return _fixedpoint(D, tol=tol, maxiter=maxiter) | python | def mle(D, tol=1e-7, method='meanprecision', maxiter=None):
'''Iteratively computes maximum likelihood Dirichlet distribution
for an observed data set, i.e. a for which log p(D|a) is maximum.
Parameters
----------
D : 2D array
``N x K`` array of numbers from [0,1] where ``N`` is the number of
observations, ``K`` is the number of parameters for the Dirichlet
distribution.
tol : float
If Euclidean distance between successive parameter arrays is less than
``tol``, calculation is taken to have converged.
method : string
One of ``'fixedpoint'`` and ``'meanprecision'``, designates method by
which to find MLE Dirichlet distribution. Default is
``'meanprecision'``, which is faster.
maxiter : int
Maximum number of iterations to take calculations. Default is
``sys.maxint``.
Returns
-------
a : array
Maximum likelihood parameters for Dirichlet distribution.'''
if method == 'meanprecision':
return _meanprecision(D, tol=tol, maxiter=maxiter)
else:
return _fixedpoint(D, tol=tol, maxiter=maxiter) | Iteratively computes maximum likelihood Dirichlet distribution
for an observed data set, i.e. a for which log p(D|a) is maximum.
Parameters
----------
D : 2D array
``N x K`` array of numbers from [0,1] where ``N`` is the number of
observations, ``K`` is the number of parameters for the Dirichlet
distribution.
tol : float
If Euclidean distance between successive parameter arrays is less than
``tol``, calculation is taken to have converged.
method : string
One of ``'fixedpoint'`` and ``'meanprecision'``, designates method by
which to find MLE Dirichlet distribution. Default is
``'meanprecision'``, which is faster.
maxiter : int
Maximum number of iterations to take calculations. Default is
``sys.maxint``.
Returns
-------
a : array
Maximum likelihood parameters for Dirichlet distribution. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L142-L171 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _fixedpoint | def _fixedpoint(D, tol=1e-7, maxiter=None):
'''Simple fixed point iteration method for MLE of Dirichlet distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _ipsi(psi(a0.sum()) + logp)
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | python | def _fixedpoint(D, tol=1e-7, maxiter=None):
'''Simple fixed point iteration method for MLE of Dirichlet distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _ipsi(psi(a0.sum()) + logp)
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | Simple fixed point iteration method for MLE of Dirichlet distribution | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L173-L189 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _meanprecision | def _meanprecision(D, tol=1e-7, maxiter=None):
'''Mean and precision alternating method for MLE of Dirichlet
distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
s0 = a0.sum()
if s0 < 0:
a0 = a0/s0
s0 = 1
elif s0 == 0:
a0 = ones(a.shape) / len(a)
s0 = 1
m0 = a0/s0
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _fit_s(D, a0, logp, tol=tol)
s1 = sum(a1)
a1 = _fit_m(D, a1, logp, tol=tol)
m = a1/s1
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | python | def _meanprecision(D, tol=1e-7, maxiter=None):
'''Mean and precision alternating method for MLE of Dirichlet
distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
s0 = a0.sum()
if s0 < 0:
a0 = a0/s0
s0 = 1
elif s0 == 0:
a0 = ones(a.shape) / len(a)
s0 = 1
m0 = a0/s0
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _fit_s(D, a0, logp, tol=tol)
s1 = sum(a1)
a1 = _fit_m(D, a1, logp, tol=tol)
m = a1/s1
# if norm(a1-a0) < tol:
if abs(loglikelihood(D, a1)-loglikelihood(D, a0)) < tol: # much faster
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, values are {}.'
.format(maxiter, a1)) | Mean and precision alternating method for MLE of Dirichlet
distribution | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L191-L219 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _fit_s | def _fit_s(D, a0, logp, tol=1e-7, maxiter=1000):
'''Assuming a fixed mean for Dirichlet distribution, maximize likelihood
for preicision a.k.a. s'''
N, K = D.shape
s1 = a0.sum()
m = a0 / s1
mlogp = (m*logp).sum()
for i in xrange(maxiter):
s0 = s1
g = psi(s1) - (m*psi(s1*m)).sum() + mlogp
h = _trigamma(s1) - ((m**2)*_trigamma(s1*m)).sum()
if g + s1 * h < 0:
s1 = 1/(1/s0 + g/h/(s0**2))
if s1 <= 0:
s1 = s0 * exp(-g/(s0*h + g)) # Newton on log s
if s1 <= 0:
s1 = 1/(1/s0 + g/((s0**2)*h + 2*s0*g)) # Newton on 1/s
if s1 <= 0:
s1 = s0 - g/h # Newton
if s1 <= 0:
raise Exception('Unable to update s from {}'.format(s0))
a = s1 * m
if abs(s1 - s0) < tol:
return a
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s1)) | python | def _fit_s(D, a0, logp, tol=1e-7, maxiter=1000):
'''Assuming a fixed mean for Dirichlet distribution, maximize likelihood
for preicision a.k.a. s'''
N, K = D.shape
s1 = a0.sum()
m = a0 / s1
mlogp = (m*logp).sum()
for i in xrange(maxiter):
s0 = s1
g = psi(s1) - (m*psi(s1*m)).sum() + mlogp
h = _trigamma(s1) - ((m**2)*_trigamma(s1*m)).sum()
if g + s1 * h < 0:
s1 = 1/(1/s0 + g/h/(s0**2))
if s1 <= 0:
s1 = s0 * exp(-g/(s0*h + g)) # Newton on log s
if s1 <= 0:
s1 = 1/(1/s0 + g/((s0**2)*h + 2*s0*g)) # Newton on 1/s
if s1 <= 0:
s1 = s0 - g/h # Newton
if s1 <= 0:
raise Exception('Unable to update s from {}'.format(s0))
a = s1 * m
if abs(s1 - s0) < tol:
return a
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s1)) | Assuming a fixed mean for Dirichlet distribution, maximize likelihood
for preicision a.k.a. s | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L221-L249 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _fit_m | def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000):
'''With fixed precision s, maximize mean m'''
N,K = D.shape
s = a0.sum()
for i in xrange(maxiter):
m = a0 / s
a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum())
a1 = a1/a1.sum() * s
if norm(a1 - a0) < tol:
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s)) | python | def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000):
'''With fixed precision s, maximize mean m'''
N,K = D.shape
s = a0.sum()
for i in xrange(maxiter):
m = a0 / s
a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum())
a1 = a1/a1.sum() * s
if norm(a1 - a0) < tol:
return a1
a0 = a1
raise Exception('Failed to converge after {} iterations, s is {}'
.format(maxiter, s)) | With fixed precision s, maximize mean m | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L251-L266 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _piecewise | def _piecewise(x, condlist, funclist, *args, **kw):
'''Fixed version of numpy.piecewise for 0-d arrays'''
x = asanyarray(x)
n2 = len(funclist)
if isscalar(condlist) or \
(isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \
(x.ndim > 0 and condlist[0].ndim == 0):
condlist = [condlist]
condlist = [asarray(c, dtype=bool) for c in condlist]
n = len(condlist)
zerod = False
# This is a hack to work around problems with NumPy's
# handling of 0-d arrays and boolean indexing with
# numpy.bool_ scalars
if x.ndim == 0:
x = x[None]
zerod = True
newcondlist = []
for k in range(n):
if condlist[k].ndim == 0:
condition = condlist[k][None]
else:
condition = condlist[k]
newcondlist.append(condition)
condlist = newcondlist
if n == n2-1: # compute the "otherwise" condition.
totlist = condlist[0]
for k in range(1, n):
totlist |= condlist[k]
condlist.append(~totlist)
n += 1
if (n != n2):
raise ValueError(
"function list and condition list must be the same")
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not callable(item):
y[condlist[k]] = item
else:
vals = x[condlist[k]]
if vals.size > 0:
y[condlist[k]] = item(vals, *args, **kw)
if zerod:
y = y.squeeze()
return y | python | def _piecewise(x, condlist, funclist, *args, **kw):
'''Fixed version of numpy.piecewise for 0-d arrays'''
x = asanyarray(x)
n2 = len(funclist)
if isscalar(condlist) or \
(isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \
(x.ndim > 0 and condlist[0].ndim == 0):
condlist = [condlist]
condlist = [asarray(c, dtype=bool) for c in condlist]
n = len(condlist)
zerod = False
# This is a hack to work around problems with NumPy's
# handling of 0-d arrays and boolean indexing with
# numpy.bool_ scalars
if x.ndim == 0:
x = x[None]
zerod = True
newcondlist = []
for k in range(n):
if condlist[k].ndim == 0:
condition = condlist[k][None]
else:
condition = condlist[k]
newcondlist.append(condition)
condlist = newcondlist
if n == n2-1: # compute the "otherwise" condition.
totlist = condlist[0]
for k in range(1, n):
totlist |= condlist[k]
condlist.append(~totlist)
n += 1
if (n != n2):
raise ValueError(
"function list and condition list must be the same")
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not callable(item):
y[condlist[k]] = item
else:
vals = x[condlist[k]]
if vals.size > 0:
y[condlist[k]] = item(vals, *args, **kw)
if zerod:
y = y.squeeze()
return y | Fixed version of numpy.piecewise for 0-d arrays | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L268-L316 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _init_a | def _init_a(D):
'''Initial guess for Dirichlet alpha parameters given data D'''
E = D.mean(axis=0)
E2 = (D**2).mean(axis=0)
return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E | python | def _init_a(D):
'''Initial guess for Dirichlet alpha parameters given data D'''
E = D.mean(axis=0)
E2 = (D**2).mean(axis=0)
return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E | Initial guess for Dirichlet alpha parameters given data D | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L318-L322 |
ericsuh/dirichlet | dirichlet/dirichlet.py | _ipsi | def _ipsi(y, tol=1.48e-9, maxiter=10):
'''Inverse of psi (digamma) using Newton's method. For the purposes
of Dirichlet MLE, since the parameters a[i] must always
satisfy a > 0, we define ipsi :: R -> (0,inf).'''
y = asanyarray(y, dtype='float')
x0 = _piecewise(y, [y >= -2.22, y < -2.22],
[(lambda x: exp(x) + 0.5), (lambda x: -1/(x+euler))])
for i in xrange(maxiter):
x1 = x0 - (psi(x0) - y)/_trigamma(x0)
if norm(x1 - x0) < tol:
return x1
x0 = x1
raise Exception(
'Unable to converge in {} iterations, value is {}'.format(maxiter, x1)) | python | def _ipsi(y, tol=1.48e-9, maxiter=10):
'''Inverse of psi (digamma) using Newton's method. For the purposes
of Dirichlet MLE, since the parameters a[i] must always
satisfy a > 0, we define ipsi :: R -> (0,inf).'''
y = asanyarray(y, dtype='float')
x0 = _piecewise(y, [y >= -2.22, y < -2.22],
[(lambda x: exp(x) + 0.5), (lambda x: -1/(x+euler))])
for i in xrange(maxiter):
x1 = x0 - (psi(x0) - y)/_trigamma(x0)
if norm(x1 - x0) < tol:
return x1
x0 = x1
raise Exception(
'Unable to converge in {} iterations, value is {}'.format(maxiter, x1)) | Inverse of psi (digamma) using Newton's method. For the purposes
of Dirichlet MLE, since the parameters a[i] must always
satisfy a > 0, we define ipsi :: R -> (0,inf). | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L324-L337 |
ericsuh/dirichlet | dirichlet/simplex.py | cartesian | def cartesian(points):
'''Converts array of barycentric coordinates on a 2-simplex to an array of
Cartesian coordinates on a 2D triangle in the first quadrant, i.e.::
>>> cartesian((1,0,0))
array([0, 0])
>>> cartesian((0,1,0))
array([0, 1])
>>> cartesian((0,0,1))
array([0.5, 0.8660254037844386]) # == [0.5, sqrt(3)/2]
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:returns: Cartesian coordinate points.
:rtype: N x 2 ndarray.'''
points = np.asanyarray(points)
ndim = points.ndim # will use this to have similar output shape to input
if ndim == 1:
points = points.reshape((1,points.size))
d = points.sum(axis=1) # in case values aren't normalized
x = 0.5*(2*points[:,1] + points[:,2])/d
y = (np.sqrt(3.0)/2) * points[:,2]/d
out = np.vstack([x,y]).T
if ndim == 1:
return out.reshape((2,))
return out | python | def cartesian(points):
'''Converts array of barycentric coordinates on a 2-simplex to an array of
Cartesian coordinates on a 2D triangle in the first quadrant, i.e.::
>>> cartesian((1,0,0))
array([0, 0])
>>> cartesian((0,1,0))
array([0, 1])
>>> cartesian((0,0,1))
array([0.5, 0.8660254037844386]) # == [0.5, sqrt(3)/2]
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:returns: Cartesian coordinate points.
:rtype: N x 2 ndarray.'''
points = np.asanyarray(points)
ndim = points.ndim # will use this to have similar output shape to input
if ndim == 1:
points = points.reshape((1,points.size))
d = points.sum(axis=1) # in case values aren't normalized
x = 0.5*(2*points[:,1] + points[:,2])/d
y = (np.sqrt(3.0)/2) * points[:,2]/d
out = np.vstack([x,y]).T
if ndim == 1:
return out.reshape((2,))
return out | Converts array of barycentric coordinates on a 2-simplex to an array of
Cartesian coordinates on a 2D triangle in the first quadrant, i.e.::
>>> cartesian((1,0,0))
array([0, 0])
>>> cartesian((0,1,0))
array([0, 1])
>>> cartesian((0,0,1))
array([0.5, 0.8660254037844386]) # == [0.5, sqrt(3)/2]
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:returns: Cartesian coordinate points.
:rtype: N x 2 ndarray. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L13-L38 |
ericsuh/dirichlet | dirichlet/simplex.py | barycentric | def barycentric(points):
'''Inverse of :func:`cartesian`.'''
points = np.asanyarray(points)
ndim = points.ndim
if ndim == 1:
points = points.reshape((1,points.size))
c = (2/np.sqrt(3.0))*points[:,1]
b = (2*points[:,0] - c)/2.0
a = 1.0 - c - b
out = np.vstack([a,b,c]).T
if ndim == 1:
return out.reshape((3,))
return out | python | def barycentric(points):
'''Inverse of :func:`cartesian`.'''
points = np.asanyarray(points)
ndim = points.ndim
if ndim == 1:
points = points.reshape((1,points.size))
c = (2/np.sqrt(3.0))*points[:,1]
b = (2*points[:,0] - c)/2.0
a = 1.0 - c - b
out = np.vstack([a,b,c]).T
if ndim == 1:
return out.reshape((3,))
return out | Inverse of :func:`cartesian`. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L40-L52 |
ericsuh/dirichlet | dirichlet/simplex.py | scatter | def scatter(points, vertexlabels=None, **kwargs):
'''Scatter plot of barycentric 2-simplex points on a 2D triangle.
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments.'''
if vertexlabels is None:
vertexlabels = ('1','2','3')
projected = cartesian(points)
plt.scatter(projected[:,0], projected[:,1], **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | python | def scatter(points, vertexlabels=None, **kwargs):
'''Scatter plot of barycentric 2-simplex points on a 2D triangle.
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments.'''
if vertexlabels is None:
vertexlabels = ('1','2','3')
projected = cartesian(points)
plt.scatter(projected[:,0], projected[:,1], **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | Scatter plot of barycentric 2-simplex points on a 2D triangle.
:param points: Points on a 2-simplex.
:type points: N x 3 list or ndarray.
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.scatter`.
:type **kwargs: keyword arguments. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L54-L72 |
ericsuh/dirichlet | dirichlet/simplex.py | contour | def contour(f, vertexlabels=None, **kwargs):
'''Contour line plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
:param f: Function to evaluate on N x 3 ndarray of coordinates
:type f: ``ufunc``
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontour, **kwargs) | python | def contour(f, vertexlabels=None, **kwargs):
'''Contour line plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
:param f: Function to evaluate on N x 3 ndarray of coordinates
:type f: ``ufunc``
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontour, **kwargs) | Contour line plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
:param f: Function to evaluate on N x 3 ndarray of coordinates
:type f: ``ufunc``
:param vertexlabels: Labels for corners of plot in the order
``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``,
``c == (0,0,1)``.
:type vertexlabels: 3-tuple of strings.
:param **kwargs: Arguments to :func:`plt.tricontour`.
:type **kwargs: keyword arguments. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L74-L86 |
ericsuh/dirichlet | dirichlet/simplex.py | contourf | def contourf(f, vertexlabels=None, **kwargs):
'''Filled contour plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
Function signature is identical to :func:`contour` with the caveat that
``**kwargs`` are passed on to :func:`plt.tricontourf`.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontourf, **kwargs) | python | def contourf(f, vertexlabels=None, **kwargs):
'''Filled contour plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
Function signature is identical to :func:`contour` with the caveat that
``**kwargs`` are passed on to :func:`plt.tricontourf`.'''
return _contour(f, vertexlabels, contourfunc=plt.tricontourf, **kwargs) | Filled contour plot on a 2D triangle of a function evaluated at
barycentric 2-simplex points.
Function signature is identical to :func:`contour` with the caveat that
``**kwargs`` are passed on to :func:`plt.tricontourf`. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L88-L94 |
ericsuh/dirichlet | dirichlet/simplex.py | _contour | def _contour(f, vertexlabels=None, contourfunc=None, **kwargs):
'''Workhorse function for the above, where ``contourfunc`` is the contour
plotting function to use for actual plotting.'''
if contourfunc is None:
contourfunc = plt.tricontour
if vertexlabels is None:
vertexlabels = ('1','2','3')
x = np.linspace(0, 1, 100)
y = np.linspace(0, np.sqrt(3.0)/2.0, 100)
points2d = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
points3d = barycentric(points2d)
valid = (points3d.sum(axis=1) == 1.0) & ((0.0 <= points3d).all(axis=1))
points2d = points2d[np.where(valid),:][0]
points3d = points3d[np.where(valid),:][0]
z = f(points3d)
contourfunc(points2d[:,0], points2d[:,1], z, **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | python | def _contour(f, vertexlabels=None, contourfunc=None, **kwargs):
'''Workhorse function for the above, where ``contourfunc`` is the contour
plotting function to use for actual plotting.'''
if contourfunc is None:
contourfunc = plt.tricontour
if vertexlabels is None:
vertexlabels = ('1','2','3')
x = np.linspace(0, 1, 100)
y = np.linspace(0, np.sqrt(3.0)/2.0, 100)
points2d = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
points3d = barycentric(points2d)
valid = (points3d.sum(axis=1) == 1.0) & ((0.0 <= points3d).all(axis=1))
points2d = points2d[np.where(valid),:][0]
points3d = points3d[np.where(valid),:][0]
z = f(points3d)
contourfunc(points2d[:,0], points2d[:,1], z, **kwargs)
_draw_axes(vertexlabels)
return plt.gcf() | Workhorse function for the above, where ``contourfunc`` is the contour
plotting function to use for actual plotting. | https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L96-L114 |
insightindustry/validator-collection | validator_collection/_decorators.py | disable_on_env | def disable_on_env(func):
"""Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``func``.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
VALIDATORS_DISABLED = os.getenv('VALIDATORS_DISABLED', '')
disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
try:
value = args[0]
except IndexError:
raise ValidatorUsageError('no value was supplied')
if function_name in disabled_functions and not force_run:
return value
else:
updated_kwargs = {key : kwargs[key]
for key in kwargs
if key != 'force_run'}
return func(*args, **updated_kwargs)
return func_wrapper | python | def disable_on_env(func):
"""Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``func``.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
VALIDATORS_DISABLED = os.getenv('VALIDATORS_DISABLED', '')
disabled_functions = [x.strip() for x in VALIDATORS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
try:
value = args[0]
except IndexError:
raise ValidatorUsageError('no value was supplied')
if function_name in disabled_functions and not force_run:
return value
else:
updated_kwargs = {key : kwargs[key]
for key in kwargs
if key != 'force_run'}
return func(*args, **updated_kwargs)
return func_wrapper | Disable the ``func`` called if its name is present in ``VALIDATORS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, the ``value`` (first positional argument) passed to
``func``. If enabled, the result of ``func``. | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L21-L53 |
insightindustry/validator-collection | validator_collection/_decorators.py | disable_checker_on_env | def disable_checker_on_env(func):
"""Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, ``True``. If enabled, the result of ``func``.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '')
disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
if function_name in disabled_functions and not force_run:
return True
else:
return func(*args, **kwargs)
return func_wrapper | python | def disable_checker_on_env(func):
"""Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, ``True``. If enabled, the result of ``func``.
"""
@wraps(func)
def func_wrapper(*args, **kwargs):
# pylint: disable=C0111, C0103
function_name = func.__name__
CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '')
disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')]
force_run = kwargs.get('force_run', False)
if function_name in disabled_functions and not force_run:
return True
else:
return func(*args, **kwargs)
return func_wrapper | Disable the ``func`` called if its name is present in ``CHECKERS_DISABLED``.
:param func: The function/validator to be disabled.
:type func: callable
:returns: If disabled, ``True``. If enabled, the result of ``func``. | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/_decorators.py#L56-L79 |
insightindustry/validator-collection | validator_collection/validators.py | uuid | def uuid(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` coerced to a :class:`UUID <python:uuid.UUID>` object /
:obj:`None <python:None>`
:rtype: :class:`UUID <python:uuid.UUID>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`UUID <python:uuid.UUID>`
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if isinstance(value, uuid_.UUID):
return value
try:
value = uuid_.UUID(value)
except ValueError:
raise errors.CannotCoerceError('value (%s) cannot be coerced to a valid UUID')
return value | python | def uuid(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` coerced to a :class:`UUID <python:uuid.UUID>` object /
:obj:`None <python:None>`
:rtype: :class:`UUID <python:uuid.UUID>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`UUID <python:uuid.UUID>`
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if isinstance(value, uuid_.UUID):
return value
try:
value = uuid_.UUID(value)
except ValueError:
raise errors.CannotCoerceError('value (%s) cannot be coerced to a valid UUID')
return value | Validate that ``value`` is a valid :class:`UUID <python:uuid.UUID>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` coerced to a :class:`UUID <python:uuid.UUID>` object /
:obj:`None <python:None>`
:rtype: :class:`UUID <python:uuid.UUID>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`UUID <python:uuid.UUID>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L133-L168 |
insightindustry/validator-collection | validator_collection/validators.py | string | def string(value,
allow_empty = False,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
"""Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum_length = integer(minimum_length, allow_empty = True)
maximum_length = integer(maximum_length, allow_empty = True)
if coerce_value:
value = str(value)
elif not isinstance(value, basestring):
raise errors.CannotCoerceError('value (%s) was not coerced to a string' % value)
if value and maximum_length and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value (%s) exceeds maximum length %s' % (value, maximum_length)
)
if value and minimum_length and len(value) < minimum_length:
if whitespace_padding:
value = value.ljust(minimum_length, ' ')
else:
raise errors.MinimumLengthError(
'value (%s) is below the minimum length %s' % (value, minimum_length)
)
return value | python | def string(value,
allow_empty = False,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
"""Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum_length = integer(minimum_length, allow_empty = True)
maximum_length = integer(maximum_length, allow_empty = True)
if coerce_value:
value = str(value)
elif not isinstance(value, basestring):
raise errors.CannotCoerceError('value (%s) was not coerced to a string' % value)
if value and maximum_length and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value (%s) exceeds maximum length %s' % (value, maximum_length)
)
if value and minimum_length and len(value) < minimum_length:
if whitespace_padding:
value = value.ljust(minimum_length, ' ')
else:
raise errors.MinimumLengthError(
'value (%s) is below the minimum length %s' % (value, minimum_length)
)
return value | Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a string if
it is not already. If ``False``, will raise a :class:`ValueError` if ``value``
is not a string. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of characters
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:param whitespace_padding: If ``True`` and the value is below the
``minimum_length``, pad the value with spaces. Defaults to ``False``.
:type whitespace_padding: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid string and ``coerce_value``
is ``False``
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L172-L245 |
insightindustry/validator-collection | validator_collection/validators.py | iterable | def iterable(value,
allow_empty = False,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Validate that ``value`` is a valid iterable.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is None:
return None
minimum_length = integer(minimum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum_length = integer(maximum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
if isinstance(value, forbid_literals) or not hasattr(value, '__iter__'):
raise errors.NotAnIterableError('value type (%s) not iterable' % type(value))
if value and minimum_length is not None and len(value) < minimum_length:
raise errors.MinimumLengthError(
'value has fewer items than the minimum length %s' % minimum_length
)
if value and maximum_length is not None and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value has more items than the maximum length %s' % maximum_length
)
return value | python | def iterable(value,
allow_empty = False,
forbid_literals = (str, bytes),
minimum_length = None,
maximum_length = None,
**kwargs):
"""Validate that ``value`` is a valid iterable.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is None:
return None
minimum_length = integer(minimum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum_length = integer(maximum_length, allow_empty = True, force_run = True) # pylint: disable=E1123
if isinstance(value, forbid_literals) or not hasattr(value, '__iter__'):
raise errors.NotAnIterableError('value type (%s) not iterable' % type(value))
if value and minimum_length is not None and len(value) < minimum_length:
raise errors.MinimumLengthError(
'value has fewer items than the minimum length %s' % minimum_length
)
if value and maximum_length is not None and len(value) > maximum_length:
raise errors.MaximumLengthError(
'value has more items than the maximum length %s' % maximum_length
)
return value | Validate that ``value`` is a valid iterable.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param forbid_literals: A collection of literals that will be considered invalid
even if they are (actually) iterable. Defaults to :class:`str <python:str>` and
:class:`bytes <python:bytes>`.
:type forbid_literals: iterable
:param minimum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type minimum_length: :class:`int <python:int>`
:param maximum_length: If supplied, indicates the minimum number of members
needed to be valid.
:type maximum_length: :class:`int <python:int>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: iterable / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotAnIterableError: if ``value`` is not a valid iterable or
:obj:`None <python:None>`
:raises MinimumLengthError: if ``minimum_length`` is supplied and the length of
``value`` is less than ``minimum_length`` and ``whitespace_padding`` is
``False``
:raises MaximumLengthError: if ``maximum_length`` is supplied and the length of
``value`` is more than the ``maximum_length`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L249-L311 |
insightindustry/validator-collection | validator_collection/validators.py | none | def none(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is :obj:`None <python:None>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty but **not** :obj:`None <python:None>`. If ``False``, raises a
:class:`NotNoneError` if ``value`` is empty but **not**
:obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: :obj:`None <python:None>`
:raises NotNoneError: if ``allow_empty`` is ``False`` and ``value`` is empty
but **not** :obj:`None <python:None>` and
"""
if value is not None and not value and allow_empty:
pass
elif (value is not None and not value) or value:
raise errors.NotNoneError('value was not None')
return None | python | def none(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is :obj:`None <python:None>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty but **not** :obj:`None <python:None>`. If ``False``, raises a
:class:`NotNoneError` if ``value`` is empty but **not**
:obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: :obj:`None <python:None>`
:raises NotNoneError: if ``allow_empty`` is ``False`` and ``value`` is empty
but **not** :obj:`None <python:None>` and
"""
if value is not None and not value and allow_empty:
pass
elif (value is not None and not value) or value:
raise errors.NotNoneError('value was not None')
return None | Validate that ``value`` is :obj:`None <python:None>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty but **not** :obj:`None <python:None>`. If ``False``, raises a
:class:`NotNoneError` if ``value`` is empty but **not**
:obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: :obj:`None <python:None>`
:raises NotNoneError: if ``allow_empty`` is ``False`` and ``value`` is empty
but **not** :obj:`None <python:None>` and | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L315-L339 |
insightindustry/validator-collection | validator_collection/validators.py | not_empty | def not_empty(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is not empty.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
"""
if not value and allow_empty:
return None
elif not value:
raise errors.EmptyValueError('value was empty')
return value | python | def not_empty(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is not empty.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
"""
if not value and allow_empty:
return None
elif not value:
raise errors.EmptyValueError('value was empty')
return value | Validate that ``value`` is not empty.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L343-L365 |
insightindustry/validator-collection | validator_collection/validators.py | variable_name | def variable_name(value,
allow_empty = False,
**kwargs):
"""Validate that the value is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or class, or
function, etc.) name.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
parse('%s = None' % value)
except (SyntaxError, ValueError, TypeError):
raise errors.InvalidVariableNameError(
'value (%s) is not a valid variable name' % value
)
return value | python | def variable_name(value,
allow_empty = False,
**kwargs):
"""Validate that the value is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or class, or
function, etc.) name.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
parse('%s = None' % value)
except (SyntaxError, ValueError, TypeError):
raise errors.InvalidVariableNameError(
'value (%s) is not a valid variable name' % value
)
return value | Validate that the value is a valid Python variable name.
.. caution::
This function does **NOT** check whether the variable exists. It only
checks that the ``value`` would work as a Python variable (or class, or
function, etc.) name.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L369-L406 |
insightindustry/validator-collection | validator_collection/validators.py | dict | def dict(value,
allow_empty = False,
json_serializer = None,
**kwargs):
"""Validate that ``value`` is a :class:`dict <python:dict>`.
.. hint::
If ``value`` is a string, this validator will assume it is a JSON
object and try to convert it into a :class:`dict <python:dict>`
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotADictError: if ``value`` is not a :class:`dict <python:dict>`
"""
original_value = value
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if json_serializer is None:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a dict' % original_value
)
value = dict(value,
json_serializer = json_serializer)
if not isinstance(value, dict_):
raise errors.NotADictError('value (%s) is not a dict' % original_value)
return value | python | def dict(value,
allow_empty = False,
json_serializer = None,
**kwargs):
"""Validate that ``value`` is a :class:`dict <python:dict>`.
.. hint::
If ``value`` is a string, this validator will assume it is a JSON
object and try to convert it into a :class:`dict <python:dict>`
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotADictError: if ``value`` is not a :class:`dict <python:dict>`
"""
original_value = value
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if json_serializer is None:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a dict' % original_value
)
value = dict(value,
json_serializer = json_serializer)
if not isinstance(value, dict_):
raise errors.NotADictError('value (%s) is not a dict' % original_value)
return value | Validate that ``value`` is a :class:`dict <python:dict>`.
.. hint::
If ``value`` is a string, this validator will assume it is a JSON
object and try to convert it into a :class:`dict <python:dict>`
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotADictError: if ``value`` is not a :class:`dict <python:dict>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L410-L470 |
insightindustry/validator-collection | validator_collection/validators.py | json | def json(value,
schema = None,
allow_empty = False,
json_serializer = None,
**kwargs):
"""Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
.. hint::
If either ``value`` or ``schema`` is a string, this validator will assume it is a
JSON object and try to convert it into a :class:`dict <python:dict>`.
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema
"""
original_value = value
original_schema = schema
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not json_serializer:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be deserialized from JSON' % original_value
)
if isinstance(schema, str):
try:
schema = dict(schema,
allow_empty = allow_empty,
json_serializer = json_serializer,
**kwargs)
except Exception:
raise errors.CannotCoerceError(
'schema (%s) cannot be coerced to a dict' % original_schema
)
if not isinstance(value, (list, dict_)):
raise errors.NotJSONError('value (%s) is not a JSON object' % original_value)
if original_schema and not isinstance(schema, dict_):
raise errors.NotJSONError('schema (%s) is not a JSON object' % original_schema)
if not schema:
return value
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as error:
raise errors.JSONValidationError(error.message)
except jsonschema.exceptions.SchemaError as error:
raise errors.NotJSONSchemaError(error.message)
return value | python | def json(value,
schema = None,
allow_empty = False,
json_serializer = None,
**kwargs):
"""Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
.. hint::
If either ``value`` or ``schema`` is a string, this validator will assume it is a
JSON object and try to convert it into a :class:`dict <python:dict>`.
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema
"""
original_value = value
original_schema = schema
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not json_serializer:
json_serializer = json_
if isinstance(value, str):
try:
value = json_serializer.loads(value)
except Exception:
raise errors.CannotCoerceError(
'value (%s) cannot be deserialized from JSON' % original_value
)
if isinstance(schema, str):
try:
schema = dict(schema,
allow_empty = allow_empty,
json_serializer = json_serializer,
**kwargs)
except Exception:
raise errors.CannotCoerceError(
'schema (%s) cannot be coerced to a dict' % original_schema
)
if not isinstance(value, (list, dict_)):
raise errors.NotJSONError('value (%s) is not a JSON object' % original_value)
if original_schema and not isinstance(schema, dict_):
raise errors.NotJSONError('schema (%s) is not a JSON object' % original_schema)
if not schema:
return value
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as error:
raise errors.JSONValidationError(error.message)
except jsonschema.exceptions.SchemaError as error:
raise errors.NotJSONSchemaError(error.message)
return value | Validate that ``value`` conforms to the supplied JSON Schema.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
.. hint::
If either ``value`` or ``schema`` is a string, this validator will assume it is a
JSON object and try to convert it into a :class:`dict <python:dict>`.
You can override the JSON serializer used by passing it to the
``json_serializer`` property. By default, will utilize the Python
:class:`json <json>` encoder/decoder.
:param value: The value to validate.
:param schema: An optional JSON Schema against which ``value`` will be validated.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param json_serializer: The JSON encoder/decoder to use to deserialize a
string passed in ``value``. If not supplied, will default to the Python
:class:`json <python:json>` encoder/decoder.
:type json_serializer: callable
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`dict <python:dict>` / :class:`list <python:list>` of
:class:`dict <python:dict>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`dict <python:dict>`
:raises NotJSONError: if ``value`` cannot be deserialized from JSON
:raises NotJSONSchemaError: if ``schema`` is not a valid JSON Schema object
:raises JSONValidationError: if ``value`` does not validate against the JSON Schema | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L474-L568 |
insightindustry/validator-collection | validator_collection/validators.py | date | def date(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid date.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a
:class:`date <python:datetime.date>` if it is a timestamp value. If ``False``,
will not.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`date <python:datetime.date>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs before
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs after
``maximum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum = date(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = date(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, date_types):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime) and coerce_value:
value = value.date()
elif isinstance(value, timestamp_types) and coerce_value:
try:
value = datetime_.date.fromtimestamp(value)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, str):
try:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
if coerce_value:
value = value.date()
else:
raise errors.CannotCoerceError(
'value (%s) must be a date object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
except ValueError:
if len(value) > 10 and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
if ' ' in value:
value = value.split(' ')[0]
if 'T' in value:
value = value.split('T')[0]
if len(value) != 10:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
try:
year = int(value[:4])
month = int(value[5:7])
day = int(value[-2:])
value = datetime_.date(year, month, day)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, numeric_types) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
if minimum and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | python | def date(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid date.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a
:class:`date <python:datetime.date>` if it is a timestamp value. If ``False``,
will not.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`date <python:datetime.date>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs before
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs after
``maximum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum = date(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = date(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, date_types):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime) and coerce_value:
value = value.date()
elif isinstance(value, timestamp_types) and coerce_value:
try:
value = datetime_.date.fromtimestamp(value)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, str):
try:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
if coerce_value:
value = value.date()
else:
raise errors.CannotCoerceError(
'value (%s) must be a date object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
except ValueError:
if len(value) > 10 and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
if ' ' in value:
value = value.split(' ')[0]
if 'T' in value:
value = value.split('T')[0]
if len(value) != 10:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
try:
year = int(value[:4])
month = int(value[5:7])
day = int(value[-2:])
value = datetime_.date(year, month, day)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value, type(value))
)
elif isinstance(value, numeric_types) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a date object, or '
'ISO 8601-formatted string, '
'but was %s' % (value, type(value))
)
if minimum and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | Validate that ``value`` is a valid date.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>`
/ :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce ``value`` to a
:class:`date <python:datetime.date>` if it is a timestamp value. If ``False``,
will not.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`date <python:datetime.date>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs before
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs after
``maximum`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L575-L712 |
insightindustry/validator-collection | validator_collection/validators.py | datetime | def datetime(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param coerce_value: If ``True``, will coerce dates to
:class:`datetime <python:datetime.datetime>` objects with times of 00:00:00. If ``False``, will error
if ``value`` is not an unambiguous timestamp. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`datetime <python:datetime.datetime>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`datetime <python:datetime.datetime>` value and is not
:obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum = datetime(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = datetime(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, datetime_types):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, timestamp_types) and coerce_value:
try:
value = datetime_.datetime.fromtimestamp(value)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, str):
# pylint: disable=line-too-long
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f%z')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y/%m/%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value, '%Y/%m/%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value,
'%Y/%m/%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value,
'%Y/%m/%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y/%m/%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value, '%Y/%m/%d %H:%M:%S')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value,
'%Y/%m/%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value,
'%Y/%m/%d %H:%M:%S')
except ValueError:
if coerce_value:
value = date(value)
else:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
# pylint: enable=line-too-long
elif isinstance(value, numeric_types) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
if isinstance(value, datetime_.date) and not isinstance(value, datetime_.datetime):
if coerce_value:
value = datetime_.datetime(value.year, # pylint: disable=R0204
value.month,
value.day,
0,
0,
0,
0)
else:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
if minimum and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | python | def datetime(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param coerce_value: If ``True``, will coerce dates to
:class:`datetime <python:datetime.datetime>` objects with times of 00:00:00. If ``False``, will error
if ``value`` is not an unambiguous timestamp. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`datetime <python:datetime.datetime>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`datetime <python:datetime.datetime>` value and is not
:obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
minimum = datetime(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = datetime(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, datetime_types):
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, timestamp_types) and coerce_value:
try:
value = datetime_.datetime.fromtimestamp(value)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a date object, datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, str):
# pylint: disable=line-too-long
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f%z')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y/%m/%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value, '%Y/%m/%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value,
'%Y/%m/%dT%H:%M:%S%z')
else:
value = datetime_.datetime.strptime(value,
'%Y/%m/%d %H:%M:%S%z')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y/%m/%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value, '%Y/%m/%d %H:%M:%S')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except ValueError:
try:
if 'T' in value:
value = datetime_.datetime.strptime(value,
'%Y/%m/%dT%H:%M:%S')
else:
value = datetime_.datetime.strptime(value,
'%Y/%m/%d %H:%M:%S')
except ValueError:
if coerce_value:
value = date(value)
else:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
# pylint: enable=line-too-long
elif isinstance(value, numeric_types) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
if isinstance(value, datetime_.date) and not isinstance(value, datetime_.datetime):
if coerce_value:
value = datetime_.datetime(value.year, # pylint: disable=R0204
value.month,
value.day,
0,
0,
0,
0)
else:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp' % value
)
if minimum and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datetime>`
/ :class:`date <python:datetime.date>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :class:`datetime <python:datetime.datetime>` /
:class:`date <python:datetime.date>` / compliant :class:`str <python:str>` /
:obj:`None <python:None>`
:param coerce_value: If ``True``, will coerce dates to
:class:`datetime <python:datetime.datetime>` objects with times of 00:00:00. If ``False``, will error
if ``value`` is not an unambiguous timestamp. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`datetime <python:datetime.datetime>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`datetime <python:datetime.datetime>` value and is not
:obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L716-L892 |
insightindustry/validator-collection | validator_collection/validators.py | time | def time(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator will
coerce the value returned back to UTC.
:param value: The value to validate.
:type value: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce/extract a
:class:`time <python:datetime.time>` from ``value``. If ``False``, will only
respect direct representations of time. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` in UTC time / :obj:`None <python:None>`
:rtype: :class:`time <python:datetime.time>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`time <python:datetime.time>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
if isinstance(value, datetime_.time):
pass
else:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
if not isinstance(value, datetime_.time):
return None
minimum = time(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = time(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, time_types):
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, datetime_.datetime) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, datetime_.datetime) and coerce_value:
value = value.time()
elif isinstance(value, timestamp_types):
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
if coerce_value:
value = datetime_value.time()
else:
raise errors.CannotCoerceError(
'value (%s) must be a time object, '
'ISO 8601-formatted string, '
'but was %s' % (value,
type(value))
)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, basestring):
is_value_calculated = False
if len(value) > 10:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
if coerce_value:
value = datetime_value.time()
else:
raise errors.CannotCoerceError(
'value (%s) must be a time object, '
'ISO 8601-formatted string, '
'but was %s' % (value,
type(value))
)
is_value_calculated = True
except ValueError:
pass
if not is_value_calculated:
try:
if '+' in value:
components = value.split('+')
is_offset_positive = True
elif '-' in value:
components = value.split('-')
is_offset_positive = False
else:
raise ValueError()
time_string = components[0]
if len(components) > 1:
utc_offset = components[1]
else:
utc_offset = None
time_components = time_string.split(':')
hour = int(time_components[0])
minutes = int(time_components[1])
seconds = time_components[2]
if '.' in seconds:
second_components = seconds.split('.')
seconds = int(second_components[0])
microseconds = int(second_components[1])
else:
microseconds = 0
utc_offset = timezone(utc_offset, # pylint: disable=E1123
allow_empty = True,
positive = is_offset_positive,
force_run = True)
value = datetime_.time(hour = hour,
minute = minutes,
second = seconds,
microsecond = microseconds,
tzinfo = utc_offset)
except (ValueError, TypeError, IndexError):
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
if value is not None:
value = value.replace(tzinfo = None)
if minimum is not None and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum is not None and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | python | def time(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator will
coerce the value returned back to UTC.
:param value: The value to validate.
:type value: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce/extract a
:class:`time <python:datetime.time>` from ``value``. If ``False``, will only
respect direct representations of time. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` in UTC time / :obj:`None <python:None>`
:rtype: :class:`time <python:datetime.time>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`time <python:datetime.time>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum``
"""
# pylint: disable=too-many-branches
if not value and not allow_empty:
if isinstance(value, datetime_.time):
pass
else:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
if not isinstance(value, datetime_.time):
return None
minimum = time(minimum, allow_empty = True, force_run = True) # pylint: disable=E1123
maximum = time(maximum, allow_empty = True, force_run = True) # pylint: disable=E1123
if not isinstance(value, time_types):
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, datetime_.datetime) and not coerce_value:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, datetime_.datetime) and coerce_value:
value = value.time()
elif isinstance(value, timestamp_types):
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
if coerce_value:
value = datetime_value.time()
else:
raise errors.CannotCoerceError(
'value (%s) must be a time object, '
'ISO 8601-formatted string, '
'but was %s' % (value,
type(value))
)
except ValueError:
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
elif isinstance(value, basestring):
is_value_calculated = False
if len(value) > 10:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
if coerce_value:
value = datetime_value.time()
else:
raise errors.CannotCoerceError(
'value (%s) must be a time object, '
'ISO 8601-formatted string, '
'but was %s' % (value,
type(value))
)
is_value_calculated = True
except ValueError:
pass
if not is_value_calculated:
try:
if '+' in value:
components = value.split('+')
is_offset_positive = True
elif '-' in value:
components = value.split('-')
is_offset_positive = False
else:
raise ValueError()
time_string = components[0]
if len(components) > 1:
utc_offset = components[1]
else:
utc_offset = None
time_components = time_string.split(':')
hour = int(time_components[0])
minutes = int(time_components[1])
seconds = time_components[2]
if '.' in seconds:
second_components = seconds.split('.')
seconds = int(second_components[0])
microseconds = int(second_components[1])
else:
microseconds = 0
utc_offset = timezone(utc_offset, # pylint: disable=E1123
allow_empty = True,
positive = is_offset_positive,
force_run = True)
value = datetime_.time(hour = hour,
minute = minutes,
second = seconds,
microsecond = microseconds,
tzinfo = utc_offset)
except (ValueError, TypeError, IndexError):
raise errors.CannotCoerceError(
'value (%s) must be a datetime object, '
'ISO 8601-formatted string, '
'or POSIX timestamp, but was %s' % (value,
type(value))
)
if value is not None:
value = value.replace(tzinfo = None)
if minimum is not None and value and value < minimum:
raise errors.MinimumValueError(
'value (%s) is before the minimum given (%s)' % (value.isoformat(),
minimum.isoformat())
)
if maximum is not None and value and value > maximum:
raise errors.MaximumValueError(
'value (%s) is after the maximum given (%s)' % (value.isoformat(),
maximum.isoformat())
)
return value | Validate that ``value`` is a valid :class:`time <python:datetime.time>`.
.. caution::
This validator will **always** return the time as timezone naive (effectively
UTC). If ``value`` has a timezone / UTC offset applied, the validator will
coerce the value returned back to UTC.
:param value: The value to validate.
:type value: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is on or after this value.
:type minimum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param maximum: If supplied, will make sure that ``value`` is on or before this
value.
:type maximum: :func:`datetime <validator_collection.validators.datetime>` or
:func:`time <validator_collection.validators.time>`-compliant
:class:`str <python:str>` / :class:`datetime <python:datetime.datetime>` /
:class:`time <python:datetime.time> / numeric / :obj:`None <python:None>`
:param coerce_value: If ``True``, will attempt to coerce/extract a
:class:`time <python:datetime.time>` from ``value``. If ``False``, will only
respect direct representations of time. Defaults to ``True``.
:type coerce_value: :class:`bool <python:bool>`
:returns: ``value`` in UTC time / :obj:`None <python:None>`
:rtype: :class:`time <python:datetime.time>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to a
:class:`time <python:datetime.time>` and is not :obj:`None <python:None>`
:raises MinimumValueError: if ``minimum`` is supplied but ``value`` occurs
before ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied but ``value`` occurs
after ``minimum`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L896-L1078 |
insightindustry/validator-collection | validator_collection/validators.py | timezone | def timezone(value,
allow_empty = False,
positive = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:
`pytz <https://pypi.python.org/pypi/pytz>`_
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`tzinfo <python:datetime.tzinfo>`
/ numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param positive: Indicates whether the ``value`` is positive or negative
(only has meaning if ``value`` is a string). Defaults to ``True``.
:type positive: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`tzinfo <python:datetime.tzinfo>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to
:class:`tzinfo <python:datetime.tzinfo>` and is not :obj:`None <python:None>`
:raises PositiveOffsetMismatchError: if ``positive`` is ``True``, but the offset
indicated by ``value`` is actually negative
:raises NegativeOffsetMismatchError: if ``positive`` is ``False``, but the offset
indicated by ``value`` is actually positive
"""
# pylint: disable=too-many-branches
original_value = value
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, tzinfo_types):
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime):
value = value.tzinfo
elif isinstance(value, datetime_.date):
return None
elif isinstance(value, datetime_.time):
return value.tzinfo
elif isinstance(value, timestamp_types):
return None
elif isinstance(value, str):
if '+' not in value and '-' not in value:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
return datetime_value.tzinfo
except TypeError:
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
elif '-' in value:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
return datetime_value.tzinfo
except TypeError:
pass
if '+' in value and not positive:
raise errors.NegativeOffsetMismatchError(
'expected a negative UTC offset but value is positive'
)
elif '-' in value and positive and len(value) == 6:
positive = False
elif '-' in value and positive:
raise errors.PositiveOffsetMismatchError(
'expected a positive UTC offset but value is negative'
)
if '+' in value:
value = value[value.find('+'):]
elif '-' in value:
value = value[value.rfind('-'):]
value = value[1:]
offset_components = value.split(':')
if len(offset_components) != 2:
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
hour = int(offset_components[0])
minutes = int(offset_components[1])
value = (hour * 60 * 60) + (minutes * 60)
if not positive:
value = 0 - value
if isinstance(value, numeric_types):
if value > 0:
positive = True
elif value < 0:
positive = False
elif value == 0:
return None
offset = datetime_.timedelta(seconds = value)
if is_py2:
value = TimeZone(offset = offset)
elif is_py3:
try:
value = TimeZone(offset)
except ValueError:
raise errors.UTCOffsetError(
'value (%s) cannot exceed +/- 24h' % original_value
)
else:
raise NotImplementedError()
return value | python | def timezone(value,
allow_empty = False,
positive = True,
**kwargs):
"""Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:
`pytz <https://pypi.python.org/pypi/pytz>`_
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`tzinfo <python:datetime.tzinfo>`
/ numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param positive: Indicates whether the ``value`` is positive or negative
(only has meaning if ``value`` is a string). Defaults to ``True``.
:type positive: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`tzinfo <python:datetime.tzinfo>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to
:class:`tzinfo <python:datetime.tzinfo>` and is not :obj:`None <python:None>`
:raises PositiveOffsetMismatchError: if ``positive`` is ``True``, but the offset
indicated by ``value`` is actually negative
:raises NegativeOffsetMismatchError: if ``positive`` is ``False``, but the offset
indicated by ``value`` is actually positive
"""
# pylint: disable=too-many-branches
original_value = value
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, tzinfo_types):
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
elif isinstance(value, datetime_.datetime):
value = value.tzinfo
elif isinstance(value, datetime_.date):
return None
elif isinstance(value, datetime_.time):
return value.tzinfo
elif isinstance(value, timestamp_types):
return None
elif isinstance(value, str):
if '+' not in value and '-' not in value:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
return datetime_value.tzinfo
except TypeError:
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
elif '-' in value:
try:
datetime_value = datetime(value, force_run = True) # pylint: disable=E1123
return datetime_value.tzinfo
except TypeError:
pass
if '+' in value and not positive:
raise errors.NegativeOffsetMismatchError(
'expected a negative UTC offset but value is positive'
)
elif '-' in value and positive and len(value) == 6:
positive = False
elif '-' in value and positive:
raise errors.PositiveOffsetMismatchError(
'expected a positive UTC offset but value is negative'
)
if '+' in value:
value = value[value.find('+'):]
elif '-' in value:
value = value[value.rfind('-'):]
value = value[1:]
offset_components = value.split(':')
if len(offset_components) != 2:
raise errors.CannotCoerceError(
'value (%s) must be a tzinfo, '
'UTC offset in seconds expressed as a number, '
'UTC offset expressed as string of form +HH:MM, '
'but was %s' % (value, type(value))
)
hour = int(offset_components[0])
minutes = int(offset_components[1])
value = (hour * 60 * 60) + (minutes * 60)
if not positive:
value = 0 - value
if isinstance(value, numeric_types):
if value > 0:
positive = True
elif value < 0:
positive = False
elif value == 0:
return None
offset = datetime_.timedelta(seconds = value)
if is_py2:
value = TimeZone(offset = offset)
elif is_py3:
try:
value = TimeZone(offset)
except ValueError:
raise errors.UTCOffsetError(
'value (%s) cannot exceed +/- 24h' % original_value
)
else:
raise NotImplementedError()
return value | Validate that ``value`` is a valid :class:`tzinfo <python:datetime.tzinfo>`.
.. caution::
This does **not** verify whether the value is a timezone that actually
exists, nor can it resolve timezone names (e.g. ``'Eastern'`` or ``'CET'``).
For that kind of functionality, we recommend you utilize:
`pytz <https://pypi.python.org/pypi/pytz>`_
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`tzinfo <python:datetime.tzinfo>`
/ numeric / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param positive: Indicates whether the ``value`` is positive or negative
(only has meaning if ``value`` is a string). Defaults to ``True``.
:type positive: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`tzinfo <python:datetime.tzinfo>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` cannot be coerced to
:class:`tzinfo <python:datetime.tzinfo>` and is not :obj:`None <python:None>`
:raises PositiveOffsetMismatchError: if ``positive`` is ``True``, but the offset
indicated by ``value`` is actually negative
:raises NegativeOffsetMismatchError: if ``positive`` is ``False``, but the offset
indicated by ``value`` is actually positive | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1082-L1219 |
insightindustry/validator-collection | validator_collection/validators.py | numeric | def numeric(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a numeric value.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises an
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form
"""
if maximum is None:
maximum = POSITIVE_INFINITY
else:
maximum = numeric(maximum)
if minimum is None:
minimum = NEGATIVE_INFINITY
else:
minimum = numeric(minimum)
if value is None and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is not None:
if isinstance(value, str):
try:
value = float_(value)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a numeric form' % value
)
elif not isinstance(value, numeric_types):
raise errors.CannotCoerceError(
'value (%s) is not a numeric type, was %s' % (value,
type(value))
)
if value is not None and value > maximum:
raise errors.MaximumValueError(
'value (%s) exceeds maximum (%s)' % (value, maximum)
)
if value is not None and value < minimum:
raise errors.MinimumValueError(
'value (%s) less than minimum (%s)' % (value, minimum)
)
return value | python | def numeric(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a numeric value.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises an
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form
"""
if maximum is None:
maximum = POSITIVE_INFINITY
else:
maximum = numeric(maximum)
if minimum is None:
minimum = NEGATIVE_INFINITY
else:
minimum = numeric(minimum)
if value is None and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif value is not None:
if isinstance(value, str):
try:
value = float_(value)
except (ValueError, TypeError):
raise errors.CannotCoerceError(
'value (%s) cannot be coerced to a numeric form' % value
)
elif not isinstance(value, numeric_types):
raise errors.CannotCoerceError(
'value (%s) is not a numeric type, was %s' % (value,
type(value))
)
if value is not None and value > maximum:
raise errors.MaximumValueError(
'value (%s) exceeds maximum (%s)' % (value, maximum)
)
if value is not None and value < minimum:
raise errors.MinimumValueError(
'value (%s) less than minimum (%s)' % (value, minimum)
)
return value | Validate that ``value`` is a numeric value.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises an
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if ``value`` cannot be coerced to a numeric form | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1225-L1295 |
insightindustry/validator-collection | validator_collection/validators.py | integer | def integer(value,
allow_empty = False,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
"""Validate that ``value`` is an :class:`int <python:int>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will force any numeric ``value`` to an integer
(always rounding up). If ``False``, will raise an error if ``value`` is numeric
but not a whole number. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises NotAnIntegerError: if ``coerce_value`` is ``False``, and ``value``
is not an integer
:raises CannotCoerceError: if ``value`` cannot be coerced to an
:class:`int <python:int>`
"""
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None and hasattr(value, 'is_integer'):
if value.is_integer():
return int(value)
if value is not None and coerce_value:
float_value = math.ceil(value)
if is_py2:
value = int(float_value) # pylint: disable=R0204
elif is_py3:
str_value = str(float_value)
value = int(str_value, base = base)
else:
raise NotImplementedError('Python %s not supported' % os.sys.version)
elif value is not None and not isinstance(value, integer_types):
raise errors.NotAnIntegerError('value (%s) is not an integer-type, '
'is a %s'% (value, type(value))
)
return value | python | def integer(value,
allow_empty = False,
coerce_value = False,
minimum = None,
maximum = None,
base = 10,
**kwargs):
"""Validate that ``value`` is an :class:`int <python:int>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will force any numeric ``value`` to an integer
(always rounding up). If ``False``, will raise an error if ``value`` is numeric
but not a whole number. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises NotAnIntegerError: if ``coerce_value`` is ``False``, and ``value``
is not an integer
:raises CannotCoerceError: if ``value`` cannot be coerced to an
:class:`int <python:int>`
"""
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None and hasattr(value, 'is_integer'):
if value.is_integer():
return int(value)
if value is not None and coerce_value:
float_value = math.ceil(value)
if is_py2:
value = int(float_value) # pylint: disable=R0204
elif is_py3:
str_value = str(float_value)
value = int(str_value, base = base)
else:
raise NotImplementedError('Python %s not supported' % os.sys.version)
elif value is not None and not isinstance(value, integer_types):
raise errors.NotAnIntegerError('value (%s) is not an integer-type, '
'is a %s'% (value, type(value))
)
return value | Validate that ``value`` is an :class:`int <python:int>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`.
Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param coerce_value: If ``True``, will force any numeric ``value`` to an integer
(always rounding up). If ``False``, will raise an error if ``value`` is numeric
but not a whole number. Defaults to ``False``.
:type coerce_value: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:param base: Indicates the base that is used to determine the integer value.
The allowed values are 0 and 2–36. Base-2, -8, and -16 literals can be
optionally prefixed with ``0b/0B``, ``0o/0O/0``, or ``0x/0X``, as with
integer literals in code. Base 0 means to interpret the string exactly as
an integer literal, so that the actual base is 2, 8, 10, or 16. Defaults to
``10``.
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises NotAnIntegerError: if ``coerce_value`` is ``False``, and ``value``
is not an integer
:raises CannotCoerceError: if ``value`` cannot be coerced to an
:class:`int <python:int>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1299-L1375 |
insightindustry/validator-collection | validator_collection/validators.py | float | def float(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`float <python:float>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`float <python:float>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`float <python:float>`
"""
try:
value = _numeric_coercion(value,
coercion_function = float_,
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum)
except (errors.EmptyValueError,
errors.CannotCoerceError,
errors.MinimumValueError,
errors.MaximumValueError) as error:
raise error
except Exception as error:
raise errors.CannotCoerceError('unable to coerce value (%s) to float, '
'for an unknown reason - please see '
'stack trace' % value)
return value | python | def float(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`float <python:float>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`float <python:float>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`float <python:float>`
"""
try:
value = _numeric_coercion(value,
coercion_function = float_,
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum)
except (errors.EmptyValueError,
errors.CannotCoerceError,
errors.MinimumValueError,
errors.MaximumValueError) as error:
raise error
except Exception as error:
raise errors.CannotCoerceError('unable to coerce value (%s) to float, '
'for an unknown reason - please see '
'stack trace' % value)
return value | Validate that ``value`` is a :class:`float <python:float>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`float <python:float>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`float <python:float>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1379-L1423 |
insightindustry/validator-collection | validator_collection/validators.py | fraction | def fraction(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Fraction <python:fractions.Fraction>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Fraction <python:fractions.Fraction>`
"""
try:
value = _numeric_coercion(value,
coercion_function = fractions.Fraction,
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum)
except (errors.EmptyValueError,
errors.CannotCoerceError,
errors.MinimumValueError,
errors.MaximumValueError) as error:
raise error
except Exception as error:
raise errors.CannotCoerceError('unable to coerce value (%s) to Fraction, '
'for an unknown reason - please see '
'stack trace' % value)
return value | python | def fraction(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Fraction <python:fractions.Fraction>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Fraction <python:fractions.Fraction>`
"""
try:
value = _numeric_coercion(value,
coercion_function = fractions.Fraction,
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum)
except (errors.EmptyValueError,
errors.CannotCoerceError,
errors.MinimumValueError,
errors.MaximumValueError) as error:
raise error
except Exception as error:
raise errors.CannotCoerceError('unable to coerce value (%s) to Fraction, '
'for an unknown reason - please see '
'stack trace' % value)
return value | Validate that ``value`` is a :class:`Fraction <python:fractions.Fraction>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Fraction <python:fractions.Fraction>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less
than the ``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more
than the ``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Fraction <python:fractions.Fraction>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1427-L1471 |
insightindustry/validator-collection | validator_collection/validators.py | decimal | def decimal(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Decimal <python:decimal.Decimal>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the
``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Decimal <python:decimal.Decimal>`
"""
if value is None and allow_empty:
return None
elif value is None:
raise errors.EmptyValueError('value cannot be None')
if isinstance(value, str):
try:
value = decimal_.Decimal(value.strip())
except decimal_.InvalidOperation:
raise errors.CannotCoerceError(
'value (%s) cannot be converted to a Decimal' % value
)
elif isinstance(value, fractions.Fraction):
try:
value = float(value, force_run = True) # pylint: disable=R0204, E1123
except ValueError:
raise errors.CannotCoerceError(
'value (%s) cannot be converted to a Decimal' % value
)
value = numeric(value, # pylint: disable=E1123
allow_empty = False,
maximum = maximum,
minimum = minimum,
force_run = True)
if not isinstance(value, decimal_.Decimal):
value = decimal_.Decimal(value)
return value | python | def decimal(value,
allow_empty = False,
minimum = None,
maximum = None,
**kwargs):
"""Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Decimal <python:decimal.Decimal>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the
``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Decimal <python:decimal.Decimal>`
"""
if value is None and allow_empty:
return None
elif value is None:
raise errors.EmptyValueError('value cannot be None')
if isinstance(value, str):
try:
value = decimal_.Decimal(value.strip())
except decimal_.InvalidOperation:
raise errors.CannotCoerceError(
'value (%s) cannot be converted to a Decimal' % value
)
elif isinstance(value, fractions.Fraction):
try:
value = float(value, force_run = True) # pylint: disable=R0204, E1123
except ValueError:
raise errors.CannotCoerceError(
'value (%s) cannot be converted to a Decimal' % value
)
value = numeric(value, # pylint: disable=E1123
allow_empty = False,
maximum = maximum,
minimum = minimum,
force_run = True)
if not isinstance(value, decimal_.Decimal):
value = decimal_.Decimal(value)
return value | Validate that ``value`` is a :class:`Decimal <python:decimal.Decimal>`.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param minimum: If supplied, will make sure that ``value`` is greater than or
equal to this value.
:type minimum: numeric
:param maximum: If supplied, will make sure that ``value`` is less than or
equal to this value.
:type maximum: numeric
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`Decimal <python:decimal.Decimal>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises MinimumValueError: if ``minimum`` is supplied and ``value`` is less than the
``minimum``
:raises MaximumValueError: if ``maximum`` is supplied and ``value`` is more than the
``maximum``
:raises CannotCoerceError: if unable to coerce ``value`` to a
:class:`Decimal <python:decimal.Decimal>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1475-L1540 |
insightindustry/validator-collection | validator_collection/validators.py | _numeric_coercion | def _numeric_coercion(value,
coercion_function = None,
allow_empty = False,
minimum = None,
maximum = None):
"""Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>`
"""
if coercion_function is None:
raise errors.CoercionFunctionEmptyError('coercion_function cannot be empty')
elif not hasattr(coercion_function, '__call__'):
raise errors.NotCallableError('coercion_function must be callable')
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None:
try:
value = coercion_function(value)
except (ValueError, TypeError, AttributeError, IndexError, SyntaxError):
raise errors.CannotCoerceError(
'cannot coerce value (%s) to desired type' % value
)
return value | python | def _numeric_coercion(value,
coercion_function = None,
allow_empty = False,
minimum = None,
maximum = None):
"""Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>`
"""
if coercion_function is None:
raise errors.CoercionFunctionEmptyError('coercion_function cannot be empty')
elif not hasattr(coercion_function, '__call__'):
raise errors.NotCallableError('coercion_function must be callable')
value = numeric(value, # pylint: disable=E1123
allow_empty = allow_empty,
minimum = minimum,
maximum = maximum,
force_run = True)
if value is not None:
try:
value = coercion_function(value)
except (ValueError, TypeError, AttributeError, IndexError, SyntaxError):
raise errors.CannotCoerceError(
'cannot coerce value (%s) to desired type' % value
)
return value | Validate that ``value`` is numeric and coerce using ``coercion_function``.
:param value: The value to validate.
:param coercion_function: The function to use to coerce ``value`` to the desired
type.
:type coercion_function: callable
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is :obj:`None <python:None>`. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if
``value`` is :obj:`None <python:None>`. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: the type returned by ``coercion_function``
:raises CoercionFunctionEmptyError: if ``coercion_function`` is empty
:raises EmptyValueError: if ``value`` is :obj:`None <python:None>` and
``allow_empty`` is ``False``
:raises CannotCoerceError: if ``coercion_function`` raises an
:class:`ValueError <python:ValueError>`, :class:`TypeError <python:TypeError>`,
:class:`AttributeError <python:AttributeError>`,
:class:`IndexError <python:IndexError>, or
:class:`SyntaxError <python:SyntaxError>` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1543-L1594 |
insightindustry/validator-collection | validator_collection/validators.py | bytesIO | def bytesIO(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotBytesIOError: if ``value`` is not a :class:`BytesIO <python:io.BytesIO>`
object.
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, io.BytesIO):
raise errors.NotBytesIOError('value (%s) is not a BytesIO, '
'is a %s' % (value, type(value)))
return value | python | def bytesIO(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotBytesIOError: if ``value`` is not a :class:`BytesIO <python:io.BytesIO>`
object.
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, io.BytesIO):
raise errors.NotBytesIOError('value (%s) is not a BytesIO, '
'is a %s' % (value, type(value)))
return value | Validate that ``value`` is a :class:`BytesIO <python:io.BytesIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`BytesIO <python:io.BytesIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotBytesIOError: if ``value`` is not a :class:`BytesIO <python:io.BytesIO>`
object. | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1600-L1629 |
insightindustry/validator-collection | validator_collection/validators.py | stringIO | def stringIO(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`StringIO <python:io.StringIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotStringIOError: if ``value`` is not a :class:`StringIO <python:io.StringIO>`
object
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, io.StringIO):
raise ValueError('value (%s) is not an io.StringIO object, '
'is a %s' % (value, type(value)))
return value | python | def stringIO(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`StringIO <python:io.StringIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotStringIOError: if ``value`` is not a :class:`StringIO <python:io.StringIO>`
object
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, io.StringIO):
raise ValueError('value (%s) is not an io.StringIO object, '
'is a %s' % (value, type(value)))
return value | Validate that ``value`` is a :class:`StringIO <python:io.StringIO>` object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`StringIO <python:io.StringIO>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises NotStringIOError: if ``value`` is not a :class:`StringIO <python:io.StringIO>`
object | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1633-L1662 |
insightindustry/validator-collection | validator_collection/validators.py | path | def path(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid path-like object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if hasattr(os, 'PathLike'):
if not isinstance(value, (str, bytes, int, os.PathLike)): # pylint: disable=E1101
raise errors.NotPathlikeError('value (%s) is path-like' % value)
else:
if not isinstance(value, int):
try:
os.path.exists(value)
except TypeError:
raise errors.NotPathlikeError('value (%s) is not path-like' % value)
return value | python | def path(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid path-like object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if hasattr(os, 'PathLike'):
if not isinstance(value, (str, bytes, int, os.PathLike)): # pylint: disable=E1101
raise errors.NotPathlikeError('value (%s) is path-like' % value)
else:
if not isinstance(value, int):
try:
os.path.exists(value)
except TypeError:
raise errors.NotPathlikeError('value (%s) is not path-like' % value)
return value | Validate that ``value`` is a valid path-like object.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The path represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value`` is empty
:raises NotPathlikeError: if ``value`` is not a valid path-like object | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1666-L1701 |
insightindustry/validator-collection | validator_collection/validators.py | path_exists | def path_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True) # pylint: disable=E1123
if not os.path.exists(value):
raise errors.PathExistsError('value (%s) not found' % value)
return value | python | def path_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True) # pylint: disable=E1123
if not os.path.exists(value):
raise errors.PathExistsError('value (%s) not found' % value)
return value | Validate that ``value`` is a path-like object that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1705-L1738 |
insightindustry/validator-collection | validator_collection/validators.py | file_exists | def file_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid file that exists on the local filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isfile(value):
raise errors.NotAFileError('value (%s) is not a file')
return value | python | def file_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid file that exists on the local filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isfile(value):
raise errors.NotAFileError('value (%s) is not a file')
return value | Validate that ``value`` is a valid file that exists on the local filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1742-L1775 |
insightindustry/validator-collection | validator_collection/validators.py | directory_exists | def directory_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid directory that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isdir(value):
raise errors.NotADirectoryError('value (%s) is not a directory' % value)
return value | python | def directory_exists(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid directory that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path_exists(value, force_run = True) # pylint: disable=E1123
if not os.path.isdir(value):
raise errors.NotADirectoryError('value (%s) is not a directory' % value)
return value | Validate that ``value`` is a valid directory that exists on the local
filesystem.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: The file name represented by ``value``.
:rtype: Path-like object / :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotADirectoryError: if ``value`` is not a valid directory | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1779-L1813 |
insightindustry/validator-collection | validator_collection/validators.py | readable | def readable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True) # pylint: disable=E1123
try:
with open(value, mode='r'):
pass
except (OSError, IOError):
raise errors.NotReadableError('file at %s could not be opened for '
'reading' % value)
return value | python | def readable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True) # pylint: disable=E1123
try:
with open(value, mode='r'):
pass
except (OSError, IOError):
raise errors.NotReadableError('file at %s could not be opened for '
'reading' % value)
return value | Validate that ``value`` is a path to a readable file.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the readability of a file *before* attempting to read it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when reading from a file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'r') as file_object:
# read from file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
:param value: The path to a file on the local filesystem whose readability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated path-like object or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises PathExistsError: if ``value`` does not exist on the local filesystem
:raises NotAFileError: if ``value`` is not a valid file
:raises NotReadableError: if ``value`` cannot be opened for reading | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1817-L1880 |
insightindustry/validator-collection | validator_collection/validators.py | writeable | def writeable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.W_OK)
if not is_valid:
raise errors.NotWriteableError('writing not allowed for file at %s' % value)
return value | python | def writeable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = path(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.W_OK)
if not is_valid:
raise errors.NotWriteableError('writing not allowed for file at %s' % value)
return value | Validate that ``value`` is a path to a writeable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the writability of a file *before* attempting to write to it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
write to the file using a ``try ... except`` block:
.. code-block:: python
try:
with open('path/to/filename.txt', mode = 'a') as file_object:
# write to file here
except (OSError, IOError) as error:
# Handle an error if unable to write.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is writeable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotWriteableError: if ``value`` cannot be opened for writing | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1883-L1968 |
insightindustry/validator-collection | validator_collection/validators.py | executable | def executable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.X_OK)
if not is_valid:
raise errors.NotExecutableError('execution not allowed for file at %s' % value)
return value | python | def executable(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a path to an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
value = file_exists(value, force_run = True)
if sys.platform in ['win32', 'cygwin']:
raise NotImplementedError('not supported on Windows')
is_valid = os.access(value, mode = os.X_OK)
if not is_valid:
raise errors.NotExecutableError('execution not allowed for file at %s' % value)
return value | Validate that ``value`` is a path to an executable file.
.. caution::
This validator does **NOT** work correctly on a Windows file system. This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permission.
If called on a Windows file system, this validator will raise
:class:`NotImplementedError() <python:NotImplementedError>`.
.. caution::
**Use of this validator is an anti-pattern and should be used with caution.**
Validating the executability of a file *before* attempting to execute it
exposes your code to a bug called
`TOCTOU <https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>`_.
This particular class of bug can expose your code to **security vulnerabilities**
and so this validator should only be used if you are an advanced user.
A better pattern to use when writing to file is to apply the principle of
EAFP ("easier to ask forgiveness than permission"), and simply attempt to
execute the file using a ``try ... except`` block.
.. note::
This validator relies on :func:`os.access() <python:os.access>` to check
whether ``value`` is executable. This function has certain limitations,
most especially that:
* It will **ignore** file-locking (yielding a false-positive) if the file
is locked.
* It focuses on *local operating system permissions*, which means if trying
to access a path over a network you might get a false positive or false
negative (because network paths may have more complicated authentication
methods).
:param value: The path to a file on the local filesystem whose writeability
is to be validated.
:type value: Path-like object
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: Validated absolute path or :obj:`None <python:None>`
:rtype: Path-like object or :obj:`None <python:None>`
:raises EmptyValueError: if ``allow_empty`` is ``False`` and ``value``
is empty
:raises NotImplementedError: if used on a Windows system
:raises NotPathlikeError: if ``value`` is not a path-like object
:raises NotAFileError: if ``value`` does not exist on the local file system
:raises NotExecutableError: if ``value`` cannot be executed | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L1971-L2049 |
insightindustry/validator-collection | validator_collection/validators.py | email | def email(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid email address.
.. note::
Email address validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of
string parsing and regular expressions.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidEmailError: if ``value`` is not a valid email address or
empty with ``allow_empty`` set to ``True``
"""
# pylint: disable=too-many-branches,too-many-statements,R0914
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '@' not in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
if '(' in value and ')' in value:
open_parentheses = value.find('(')
close_parentheses = value.find(')') + 1
if close_parentheses < open_parentheses:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
commented_value = value[open_parentheses:close_parentheses]
value = value.replace(commented_value, '')
elif '(' in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
elif ')' in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
if '<' in value or '>' in value:
lt_position = value.find('<')
gt_position = value.find('>')
first_quote_position = -1
second_quote_position = -1
if lt_position >= 0:
first_quote_position = value.find('"', 0, lt_position)
if gt_position >= 0:
second_quote_position = value.find('"', gt_position)
if first_quote_position < 0 or second_quote_position < 0:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
at_count = value.count('@')
if at_count > 1:
last_at_position = 0
last_quote_position = 0
for x in range(0, at_count): # pylint: disable=W0612
at_position = value.find('@', last_at_position + 1)
if at_position >= 0:
first_quote_position = value.find('"',
last_quote_position,
at_position)
second_quote_position = value.find('"',
first_quote_position)
if first_quote_position < 0 or second_quote_position < 0:
raise errors.InvalidEmailError(
'value (%s) is not a valid email address' % value
)
last_at_position = at_position
last_quote_position = second_quote_position
split_values = value.split('@')
if len(split_values) < 2:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
local_value = ''.join(split_values[:-1])
domain_value = split_values[-1]
is_domain = False
is_ip = False
try:
if domain_value.startswith('[') and domain_value.endswith(']'):
domain_value = domain_value[1:-1]
domain(domain_value)
is_domain = True
except ValueError:
is_domain = False
if not is_domain:
try:
ip_address(domain_value, force_run = True) # pylint: disable=E1123
is_ip = True
except ValueError:
is_ip = False
if not is_domain and is_ip:
try:
email(local_value + '@test.com', force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
return value
if not is_domain:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
else:
is_valid = EMAIL_REGEX.search(value)
if not is_valid:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
matched_string = is_valid.group(0)
position = value.find(matched_string)
if position > 0:
prefix = value[:position]
if prefix[0] in string_.punctuation:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
if '..' in prefix:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
end_of_match = position + len(matched_string)
suffix = value[end_of_match:]
if suffix:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
return value | python | def email(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid email address.
.. note::
Email address validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of
string parsing and regular expressions.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidEmailError: if ``value`` is not a valid email address or
empty with ``allow_empty`` set to ``True``
"""
# pylint: disable=too-many-branches,too-many-statements,R0914
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '@' not in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
if '(' in value and ')' in value:
open_parentheses = value.find('(')
close_parentheses = value.find(')') + 1
if close_parentheses < open_parentheses:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
commented_value = value[open_parentheses:close_parentheses]
value = value.replace(commented_value, '')
elif '(' in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
elif ')' in value:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
if '<' in value or '>' in value:
lt_position = value.find('<')
gt_position = value.find('>')
first_quote_position = -1
second_quote_position = -1
if lt_position >= 0:
first_quote_position = value.find('"', 0, lt_position)
if gt_position >= 0:
second_quote_position = value.find('"', gt_position)
if first_quote_position < 0 or second_quote_position < 0:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
at_count = value.count('@')
if at_count > 1:
last_at_position = 0
last_quote_position = 0
for x in range(0, at_count): # pylint: disable=W0612
at_position = value.find('@', last_at_position + 1)
if at_position >= 0:
first_quote_position = value.find('"',
last_quote_position,
at_position)
second_quote_position = value.find('"',
first_quote_position)
if first_quote_position < 0 or second_quote_position < 0:
raise errors.InvalidEmailError(
'value (%s) is not a valid email address' % value
)
last_at_position = at_position
last_quote_position = second_quote_position
split_values = value.split('@')
if len(split_values) < 2:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
local_value = ''.join(split_values[:-1])
domain_value = split_values[-1]
is_domain = False
is_ip = False
try:
if domain_value.startswith('[') and domain_value.endswith(']'):
domain_value = domain_value[1:-1]
domain(domain_value)
is_domain = True
except ValueError:
is_domain = False
if not is_domain:
try:
ip_address(domain_value, force_run = True) # pylint: disable=E1123
is_ip = True
except ValueError:
is_ip = False
if not is_domain and is_ip:
try:
email(local_value + '@test.com', force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
return value
if not is_domain:
raise errors.InvalidEmailError('value (%s) is not a valid email address' % value)
else:
is_valid = EMAIL_REGEX.search(value)
if not is_valid:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
matched_string = is_valid.group(0)
position = value.find(matched_string)
if position > 0:
prefix = value[:position]
if prefix[0] in string_.punctuation:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
if '..' in prefix:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
end_of_match = position + len(matched_string)
suffix = value[end_of_match:]
if suffix:
raise errors.InvalidEmailError('value (%s) is not a valid email '
'address' % value)
return value | Validate that ``value`` is a valid email address.
.. note::
Email address validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 5322 <https://tools.ietf.org/html/rfc5322>`_ and uses a combination of
string parsing and regular expressions.
String parsing in particular is used to validate certain *highly unusual*
but still valid email patterns, including the use of escaped text and
comments within an email address' local address (the user name part).
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidEmailError: if ``value`` is not a valid email address or
empty with ``allow_empty`` set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2055-L2212 |
insightindustry/validator-collection | validator_collection/validators.py | url | def url(value,
allow_empty = False,
allow_special_ips = False,
**kwargs):
"""Validate that ``value`` is a valid URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True``
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
value = value.lower()
is_valid = False
stripped_value = None
for protocol in URL_PROTOCOLS:
if protocol in value:
stripped_value = value.replace(protocol, '')
for special_use_domain in SPECIAL_USE_DOMAIN_NAMES:
if special_use_domain in value:
if stripped_value:
try:
domain(stripped_value,
allow_empty = False,
is_recursive = is_recursive)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid and allow_special_ips:
try:
ip_address(stripped_value, allow_empty = False)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid:
is_valid = URL_REGEX.match(value)
if not is_valid and allow_special_ips:
is_valid = URL_SPECIAL_IP_REGEX.match(value)
if not is_valid:
raise errors.InvalidURLError('value (%s) is not a valid URL' % value)
return value | python | def url(value,
allow_empty = False,
allow_special_ips = False,
**kwargs):
"""Validate that ``value`` is a valid URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True``
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
value = value.lower()
is_valid = False
stripped_value = None
for protocol in URL_PROTOCOLS:
if protocol in value:
stripped_value = value.replace(protocol, '')
for special_use_domain in SPECIAL_USE_DOMAIN_NAMES:
if special_use_domain in value:
if stripped_value:
try:
domain(stripped_value,
allow_empty = False,
is_recursive = is_recursive)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid and allow_special_ips:
try:
ip_address(stripped_value, allow_empty = False)
is_valid = True
except (ValueError, TypeError):
pass
if not is_valid:
is_valid = URL_REGEX.match(value)
if not is_valid and allow_special_ips:
is_valid = URL_SPECIAL_IP_REGEX.match(value)
if not is_valid:
raise errors.InvalidURLError('value (%s) is not a valid URL' % value)
return value | Validate that ``value`` is a valid URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
`RFC 2181 <https://tools.ietf.org/html/rfc2181>`_ and uses a combination of
string parsing and regular expressions,
This approach ensures more complete coverage for unusual edge cases, while
still letting us use regular expressions that perform quickly.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_special_ips: If ``True``, will succeed when validating special IP
addresses, such as loopback IPs like ``127.0.0.1`` or ``0.0.0.0``. If ``False``,
will raise a :class:`InvalidURLError` if ``value`` is a special IP address. Defaults
to ``False``.
:type allow_special_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidURLError: if ``value`` is not a valid URL or
empty with ``allow_empty`` set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2216-L2306 |
insightindustry/validator-collection | validator_collection/validators.py | domain | def domain(value,
allow_empty = False,
allow_ips = False,
**kwargs):
"""Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '/' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "/"')
if '\\' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "\\"')
if '@' in value:
raise errors.AtInDomainError('valid domain name cannot contain "@"')
if ':' in value:
raise errors.ColonInDomainError('valid domain name cannot contain ":"')
value = value.strip().lower()
for item in string_.whitespace:
if item in value:
raise errors.WhitespaceInDomainError('valid domain name cannot contain '
'whitespace')
if value in SPECIAL_USE_DOMAIN_NAMES:
return value
if allow_ips:
try:
ip_address(value, allow_empty = allow_empty)
is_valid = True
except (ValueError, TypeError, AttributeError):
is_valid = False
if is_valid:
return value
is_valid = DOMAIN_REGEX.match(value)
if not is_valid and not is_recursive:
with_prefix = 'http://' + value
try:
url(with_prefix, force_run = True, is_recursive = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidDomainError('value (%s) is not a valid domain' % value)
return value | python | def domain(value,
allow_empty = False,
allow_ips = False,
**kwargs):
"""Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace
"""
is_recursive = kwargs.pop('is_recursive', False)
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '/' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "/"')
if '\\' in value:
raise errors.SlashInDomainError('valid domain name cannot contain "\\"')
if '@' in value:
raise errors.AtInDomainError('valid domain name cannot contain "@"')
if ':' in value:
raise errors.ColonInDomainError('valid domain name cannot contain ":"')
value = value.strip().lower()
for item in string_.whitespace:
if item in value:
raise errors.WhitespaceInDomainError('valid domain name cannot contain '
'whitespace')
if value in SPECIAL_USE_DOMAIN_NAMES:
return value
if allow_ips:
try:
ip_address(value, allow_empty = allow_empty)
is_valid = True
except (ValueError, TypeError, AttributeError):
is_valid = False
if is_valid:
return value
is_valid = DOMAIN_REGEX.match(value)
if not is_valid and not is_recursive:
with_prefix = 'http://' + value
try:
url(with_prefix, force_run = True, is_recursive = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidDomainError('value (%s) is not a valid domain' % value)
return value | Validate that ``value`` is a valid domain name.
.. caution::
This validator does not verify that ``value`` **exists** as a domain. It
merely verifies that its contents *might* exist as a domain.
.. note::
This validator checks to validate that ``value`` resembles a valid
domain name. It is - generally - compliant with
`RFC 1035 <https://tools.ietf.org/html/rfc1035>`_ and
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_, however it diverges
in a number of key ways:
* Including authentication (e.g. ``username:[email protected]``) will
fail validation.
* Including a path (e.g. ``domain.dev/path/to/file``) will fail validation.
* Including a port (e.g. ``domain.dev:8080``) will fail validation.
If you are hoping to validate a more complete URL, we recommend that you
see :func:`url <validator_collection.validators.url>`.
.. hint::
Leading and trailing whitespace will be automatically stripped.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:param allow_ips: If ``True``, will succeed when validating IP addresses,
If ``False``, will raise a :class:`InvalidDomainError` if ``value`` is an IP
address. Defaults to ``False``.
:type allow_ips: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a :class:`str <python:str>` or
:obj:`None <python:None>`
:raises InvalidDomainError: if ``value`` is not a valid domain name or
empty with ``allow_empty`` set to ``True``
:raises SlashInDomainError: if ``value`` contains a slash or backslash
:raises AtInDomainError: if ``value`` contains an ``@`` symbol
:raises ColonInDomainError: if ``value`` contains a ``:`` symbol
:raises WhitespaceInDomainError: if ``value`` contains whitespace | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2310-L2418 |
insightindustry/validator-collection | validator_collection/validators.py | ip_address | def ip_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv4 address.
If neither works, the validator will raise an error (as always).
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if is_py2 and value and isinstance(value, unicode):
value = value.encode('utf-8')
try:
value = ipv6(value, force_run = True) # pylint: disable=E1123
ipv6_failed = False
except ValueError:
ipv6_failed = True
if ipv6_failed:
try:
value = ipv4(value, force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid IPv6 or '
'IPv4 address' % value)
return value | python | def ip_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv4 address.
If neither works, the validator will raise an error (as always).
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if is_py2 and value and isinstance(value, unicode):
value = value.encode('utf-8')
try:
value = ipv6(value, force_run = True) # pylint: disable=E1123
ipv6_failed = False
except ValueError:
ipv6_failed = True
if ipv6_failed:
try:
value = ipv4(value, force_run = True) # pylint: disable=E1123
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid IPv6 or '
'IPv4 address' % value)
return value | Validate that ``value`` is a valid IP address.
.. note::
First, the validator will check if the address is a valid IPv6 address.
If that doesn't work, the validator will check if the address is a valid
IPv4 address.
If neither works, the validator will raise an error (as always).
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP address or empty with
``allow_empty`` set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2422-L2471 |
insightindustry/validator-collection | validator_collection/validators.py | ipv4 | def ipv4(value, allow_empty = False):
"""Validate that ``value`` is a valid IP version 4 address.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
components = value.split('.')
except AttributeError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
if len(components) != 4 or not all(x.isdigit() for x in components):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
for x in components:
try:
x = integer(x,
minimum = 0,
maximum = 255)
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
return value | python | def ipv4(value, allow_empty = False):
"""Validate that ``value`` is a valid IP version 4 address.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
try:
components = value.split('.')
except AttributeError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
if len(components) != 4 or not all(x.isdigit() for x in components):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
for x in components:
try:
x = integer(x,
minimum = 0,
maximum = 255)
except ValueError:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv4' % value)
return value | Validate that ``value`` is a valid IP version 4 address.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 4 address or
empty with ``allow_empty`` set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2475-L2513 |
insightindustry/validator-collection | validator_collection/validators.py | ipv6 | def ipv6(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid IP address version 6.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, str):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
value = value.lower().strip()
is_valid = IPV6_REGEX.match(value)
if not is_valid:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
return value | python | def ipv6(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid IP address version 6.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True``
"""
if not value and allow_empty is False:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, str):
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
value = value.lower().strip()
is_valid = IPV6_REGEX.match(value)
if not is_valid:
raise errors.InvalidIPAddressError('value (%s) is not a valid ipv6' % value)
return value | Validate that ``value`` is a valid IP address version 6.
:param value: The value to validate.
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises InvalidIPAddressError: if ``value`` is not a valid IP version 6 address or
empty with ``allow_empty`` is not set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2517-L2552 |
insightindustry/validator-collection | validator_collection/validators.py | mac_address | def mac_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '-' in value:
value = value.replace('-', ':')
value = value.lower().strip()
is_valid = MAC_ADDRESS_REGEX.match(value)
if not is_valid:
raise errors.InvalidMACAddressError('value (%s) is not a valid MAC '
'address' % value)
return value | python | def mac_address(value,
allow_empty = False,
**kwargs):
"""Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True``
"""
if not value and not allow_empty:
raise errors.EmptyValueError('value (%s) was empty' % value)
elif not value:
return None
if not isinstance(value, basestring):
raise errors.CannotCoerceError('value must be a valid string, '
'was %s' % type(value))
if '-' in value:
value = value.replace('-', ':')
value = value.lower().strip()
is_valid = MAC_ADDRESS_REGEX.match(value)
if not is_valid:
raise errors.InvalidMACAddressError('value (%s) is not a valid MAC '
'address' % value)
return value | Validate that ``value`` is a valid MAC address.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if
``value`` is empty. If ``False``, raises a
:class:`EmptyValueError <validator_collection.errors.EmptyValueError>`
if ``value`` is empty. Defaults to ``False``.
:type allow_empty: :class:`bool <python:bool>`
:returns: ``value`` / :obj:`None <python:None>`
:rtype: :class:`str <python:str>` / :obj:`None <python:None>`
:raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False``
:raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>`
or string-like object
:raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with
``allow_empty`` set to ``True`` | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L2556-L2600 |
insightindustry/validator-collection | validator_collection/checkers.py | is_type | def is_type(obj,
type_,
**kwargs):
"""Indicate if ``obj`` is a type in ``type_``.
.. hint::
This checker is particularly useful when you want to evaluate whether
``obj`` is of a particular type, but importing that type directly to use
in :func:`isinstance() <python:isinstance>` would cause a circular import
error.
To use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if not is_iterable(type_):
type_ = [type_]
return_value = False
for check_for_type in type_:
if isinstance(check_for_type, type):
return_value = isinstance(obj, check_for_type)
elif obj.__class__.__name__ == check_for_type:
return_value = True
else:
return_value = _check_base_classes(obj.__class__.__bases__,
check_for_type)
if return_value is True:
break
return return_value | python | def is_type(obj,
type_,
**kwargs):
"""Indicate if ``obj`` is a type in ``type_``.
.. hint::
This checker is particularly useful when you want to evaluate whether
``obj`` is of a particular type, but importing that type directly to use
in :func:`isinstance() <python:isinstance>` would cause a circular import
error.
To use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator
"""
if not is_iterable(type_):
type_ = [type_]
return_value = False
for check_for_type in type_:
if isinstance(check_for_type, type):
return_value = isinstance(obj, check_for_type)
elif obj.__class__.__name__ == check_for_type:
return_value = True
else:
return_value = _check_base_classes(obj.__class__.__bases__,
check_for_type)
if return_value is True:
break
return return_value | Indicate if ``obj`` is a type in ``type_``.
.. hint::
This checker is particularly useful when you want to evaluate whether
``obj`` is of a particular type, but importing that type directly to use
in :func:`isinstance() <python:isinstance>` would cause a circular import
error.
To use this checker in that kind of situation, you can instead pass the
*name* of the type you want to check as a string in ``type_``. The checker
will evaluate it and see whether ``obj`` is of a type or inherits from a
type whose name matches the string you passed.
:param obj: The object whose type should be checked.
:type obj: :class:`object <python:object>`
:param type_: The type(s) to check against.
:type type_: :class:`type <python:type>` / iterable of :class:`type <python:type>` /
:class:`str <python:str>` with type name / iterable of :class:`str <python:str>`
with type name
:returns: ``True`` if ``obj`` is a type in ``type_``. Otherwise, ``False``.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates
keyword parameters passed to the underlying validator | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L21-L69 |
insightindustry/validator-collection | validator_collection/checkers.py | _check_base_classes | def _check_base_classes(base_classes, check_for_type):
"""Indicate whether ``check_for_type`` exists in ``base_classes``.
"""
return_value = False
for base in base_classes:
if base.__name__ == check_for_type:
return_value = True
break
else:
return_value = _check_base_classes(base.__bases__, check_for_type)
if return_value is True:
break
return return_value | python | def _check_base_classes(base_classes, check_for_type):
"""Indicate whether ``check_for_type`` exists in ``base_classes``.
"""
return_value = False
for base in base_classes:
if base.__name__ == check_for_type:
return_value = True
break
else:
return_value = _check_base_classes(base.__bases__, check_for_type)
if return_value is True:
break
return return_value | Indicate whether ``check_for_type`` exists in ``base_classes``. | https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L72-L85 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.