Added LocaleType
This commit is contained in:
@@ -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,
|
||||
|
@@ -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,
|
||||
|
40
sqlalchemy_utils/types/locale.py
Normal file
40
sqlalchemy_utils/types/locale.py
Normal file
@@ -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
|
@@ -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')
|
||||
)
|
||||
|
Reference in New Issue
Block a user