1from ipaddress import ip_address
2
3from sqlalchemy import types
4
5from .scalar_coercible import ScalarCoercible
6
7
8class IPAddressType(ScalarCoercible, types.TypeDecorator):
9 """
10 Changes IPAddress objects to a string representation on the way in and
11 changes them back to IPAddress objects on the way out.
12
13 ::
14
15
16 from sqlalchemy_utils import IPAddressType
17
18
19 class User(Base):
20 __tablename__ = 'user'
21 id = sa.Column(sa.Integer, autoincrement=True)
22 name = sa.Column(sa.Unicode(255))
23 ip_address = sa.Column(IPAddressType)
24
25
26 user = User()
27 user.ip_address = '123.123.123.123'
28 session.add(user)
29 session.commit()
30
31 user.ip_address # IPAddress object
32 """
33
34 impl = types.Unicode(50)
35 cache_ok = True
36
37 def __init__(self, max_length=50, *args, **kwargs):
38 super().__init__(*args, **kwargs)
39 self.impl = types.Unicode(max_length)
40
41 def process_bind_param(self, value, dialect):
42 return str(value) if value else None
43
44 def process_result_value(self, value, dialect):
45 return ip_address(value) if value else None
46
47 def _coerce(self, value):
48 return ip_address(value) if value else None
49
50 @property
51 def python_type(self):
52 return self.impl.type.python_type