1from sqlalchemy import types
2
3from ..exceptions import ImproperlyConfigured
4from .scalar_coercible import ScalarCoercible
5
6babel = None
7try:
8 import babel
9except ImportError:
10 pass
11
12
13class LocaleType(ScalarCoercible, types.TypeDecorator):
14 """
15 LocaleType saves Babel_ Locale objects into database. The Locale objects
16 are converted to string on the way in and back to object on the way out.
17
18 In order to use LocaleType you need to install Babel_ first.
19
20 .. _Babel: https://babel.pocoo.org/
21
22 ::
23
24
25 from sqlalchemy_utils import LocaleType
26 from babel import Locale
27
28
29 class User(Base):
30 __tablename__ = 'user'
31 id = sa.Column(sa.Integer, autoincrement=True)
32 name = sa.Column(sa.Unicode(50))
33 locale = sa.Column(LocaleType)
34
35
36 user = User()
37 user.locale = Locale('en_US')
38 session.add(user)
39 session.commit()
40
41
42 Like many other types this type also supports scalar coercion:
43
44 ::
45
46
47 user.locale = 'de_DE'
48 user.locale # Locale('de', territory='DE')
49
50 """
51
52 impl = types.Unicode(10)
53
54 cache_ok = True
55
56 def __init__(self):
57 if babel is None:
58 raise ImproperlyConfigured('Babel packaged is required with LocaleType.')
59
60 def process_bind_param(self, value, dialect):
61 if isinstance(value, babel.Locale):
62 return str(value)
63
64 if isinstance(value, str):
65 return value
66
67 def process_result_value(self, value, dialect):
68 if value is not None:
69 return babel.Locale.parse(value)
70
71 def _coerce(self, value):
72 if value is not None and not isinstance(value, babel.Locale):
73 return babel.Locale.parse(value)
74 return value