diff --git a/sqlalchemy_utils/__init__.py b/sqlalchemy_utils/__init__.py index 4ced43c..6dd274f 100644 --- a/sqlalchemy_utils/__init__.py +++ b/sqlalchemy_utils/__init__.py @@ -26,6 +26,7 @@ from .types import ( instrumented_list, InstrumentedList, IPAddressType, + LocaleType, Password, PasswordType, PhoneNumber, @@ -71,6 +72,7 @@ __all__ = ( ImproperlyConfigured, InstrumentedList, IPAddressType, + LocaleType, Merger, NumberRange, NumberRangeException, diff --git a/sqlalchemy_utils/types/__init__.py b/sqlalchemy_utils/types/__init__.py index 1f89474..854f56a 100644 --- a/sqlalchemy_utils/types/__init__.py +++ b/sqlalchemy_utils/types/__init__.py @@ -5,6 +5,7 @@ from .color import ColorType from .country import CountryType, Country from .email import EmailType from .ip_address import IPAddressType +from .locale import LocaleType from .number_range import ( NumberRange, NumberRangeException, @@ -28,6 +29,7 @@ __all__ = ( Country, EmailType, IPAddressType, + LocaleType, NumberRange, NumberRangeException, NumberRangeRawType, diff --git a/sqlalchemy_utils/types/locale.py b/sqlalchemy_utils/types/locale.py new file mode 100644 index 0000000..d2f5691 --- /dev/null +++ b/sqlalchemy_utils/types/locale.py @@ -0,0 +1,40 @@ +from sqlalchemy import types +import six +from .scalar_coercible import ScalarCoercible +from ..exceptions import ImproperlyConfigured +babel = None +try: + import babel +except ImportError: + pass + + +class LocaleType(types.TypeDecorator, ScalarCoercible): + """ + Changes babel.Locale objects to a string representation on the way in and + changes them back to Locale objects on the way out. + """ + + impl = types.Unicode(10) + + def __init__(self): + if babel is None: + raise ImproperlyConfigured( + 'Babel packaged is required with LocaleType.' + ) + + def process_bind_param(self, value, dialect): + if isinstance(value, babel.Locale): + return six.text_type(value) + + if isinstance(value, six.string_types): + return value + + def process_result_value(self, value, dialect): + if value is not None: + return babel.Locale(value) + + def _coerce(self, value): + if value is not None and not isinstance(value, babel.Locale): + return babel.Locale(value) + return value diff --git a/tests/types/test_country.py b/tests/types/test_country.py index 0e3d05b..83607a7 100644 --- a/tests/types/test_country.py +++ b/tests/types/test_country.py @@ -39,7 +39,7 @@ class TestCountryType(TestCase): self.User = User - def test_color_parameter_processing(self): + def test_parameter_processing(self): user = self.User( country=Country(u'fi') )