Last active
June 11, 2018 04:58
-
-
Save lotusirous/8380f99e303fee06b083f61057d61f74 to your computer and use it in GitHub Desktop.
voluptuous IP address validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipaddress | |
from voluptuous.schema_builder import message | |
from voluptuous import All, Invalid, Required, Schema | |
from voluptuous.error import Invalid | |
class IPInvalid(Invalid): | |
"""The value is not valid IP.""" | |
@message('expected an IP address', cls=IPInvalid) | |
def IPAddr(v): | |
"""Verify that the value is an IP or not. | |
Support validate IPv4 or IPv6 | |
>>> s = Schema(validIP()) | |
>>> with raises(MultipleInvalid, 'expected an IP address'): | |
... s("127.0.0.1") | |
>>> with raises(MultipleInvalid, 'expected an IP address'): | |
... s("192.168.0.1") | |
>>> with raises(MultipleInvalid, 'expected an IP address'): | |
... s("0.0.0.0") | |
>>> s('1.1.1.1') | |
'1.1.1.1' | |
""" | |
try: | |
if not v: | |
raise IPInvalid("expected an IP address") | |
# this function only available in python 3 | |
ipaddress.ip_address(v) | |
return v | |
except: | |
raise ValueError | |
# Run example | |
from voluptuous import ALLOW_EXTRA, All, Required, Schema, Optional, MultipleInvalid | |
schema = Schema({ | |
Required('ip'): All(IPAddr()), | |
Required('name'): str, | |
Optional('description'): str | |
}, extra=ALLOW_EXTRA) | |
print(schema({ | |
"ip": "127.3.0.1.1", | |
"name": "sdf", | |
"description": "sdf", | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment