web: model: Host: Add validation properties
parent
5e72a216ed
commit
83072c0db7
|
@ -1,6 +1,8 @@
|
||||||
from __future__ import unicode_literals
|
from __future__ import unicode_literals
|
||||||
from sqlalchemy import schema, types, orm
|
from sqlalchemy import schema, types, orm
|
||||||
from sqlalchemy.ext import declarative
|
from sqlalchemy.ext import declarative
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
|
||||||
|
|
||||||
Base = declarative.declarative_base()
|
Base = declarative.declarative_base()
|
||||||
|
@ -27,9 +29,54 @@ class Serializable(object):
|
||||||
|
|
||||||
class Host(Base, Serializable):
|
class Host(Base, Serializable):
|
||||||
|
|
||||||
|
HOSTNAME_RE = re.compile(
|
||||||
|
r'^(?=.{1,255}$)(?:(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)*'
|
||||||
|
r'(?![0-9]+$)(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.?$'
|
||||||
|
)
|
||||||
|
MACADDR_RE = re.compile(
|
||||||
|
r'(([0-9a-f]{2}[:-]){5}[0-9a-f]{2})|'
|
||||||
|
r'(([0-9a-f]{4}\.){2}[0-9a-f]{4})',
|
||||||
|
re.IGNORECASE
|
||||||
|
)
|
||||||
__tablename__ = 'hosts'
|
__tablename__ = 'hosts'
|
||||||
|
|
||||||
id = schema.Column(types.Integer, autoincrement=True, primary_key=True)
|
id = schema.Column(types.Integer, autoincrement=True, primary_key=True)
|
||||||
macaddr = schema.Column(types.String(18), nullable=False)
|
_macaddr = schema.Column('macaddr', types.String(18), nullable=False)
|
||||||
ipaddr = schema.Column(types.String(46))
|
_ipaddr = schema.Column('ipaddr', types.String(46))
|
||||||
hostname = schema.Column(types.Unicode(253))
|
_hostname = schema.Column('hostname', types.Unicode(253))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def macaddr(self):
|
||||||
|
return self._macaddr
|
||||||
|
|
||||||
|
@macaddr.setter
|
||||||
|
def macaddr(self, value):
|
||||||
|
if not self.MACADDR_RE.match(value):
|
||||||
|
raise ValueError('Invalid MAC address: {}'.format(value))
|
||||||
|
self._macaddr = value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def ipaddr(self):
|
||||||
|
return self._ipaddr
|
||||||
|
|
||||||
|
@ipaddr.setter
|
||||||
|
def ipaddr(self, value):
|
||||||
|
if ':' in value:
|
||||||
|
af = socket.AF_INET6
|
||||||
|
else:
|
||||||
|
af = socket.AF_INET
|
||||||
|
try:
|
||||||
|
packed = socket.inet_pton(af, value)
|
||||||
|
except socket.error as e:
|
||||||
|
raise ValueError('{}: {}'.format(e, value))
|
||||||
|
self._ipaddr = socket.inet_ntop(af, packed)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def hostname(self):
|
||||||
|
return self._hostname
|
||||||
|
|
||||||
|
@hostname.setter
|
||||||
|
def hostname(self, value):
|
||||||
|
if not self.HOSTNAME_RE.match(value):
|
||||||
|
raise ValueError('Invalid hostname: {}'.format(value))
|
||||||
|
self._hostname = value
|
||||||
|
|
Loading…
Reference in New Issue