How to use the schematics.translator._ function in schematics

To help you get started, we’ve selected a few schematics examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github schematics / schematics / schematics / types / compound.py View on Github external
def check_length(self, value, context):
        list_length = len(value) if value else 0

        if self.min_size is not None and list_length < self.min_size:
            message = ({
                True: _('Please provide at least %d item.'),
                False: _('Please provide at least %d items.'),
            }[self.min_size == 1]) % self.min_size
            raise ValidationError(message)

        if self.max_size is not None and list_length > self.max_size:
            message = ({
                True: _('Please provide no more than %d item.'),
                False: _('Please provide no more than %d items.'),
            }[self.max_size == 1]) % self.max_size
            raise ValidationError(message)
github schematics / schematics / schematics / types / base.py View on Github external
raise ValidationError(self.messages['regex'])


class NumberType(BaseType):

    """A generic number field.
    Converts to and validates against `number_type` parameter.
    """

    primitive_type = None
    native_type = None
    number_type = None
    MESSAGES = {
        'number_coerce': _("Value '{0}' is not {1}."),
        'number_min': _("{0} value should be greater than or equal to {1}."),
        'number_max': _("{0} value should be less than or equal to {1}."),
    }

    def __init__(self, min_value=None, max_value=None, strict=False, **kwargs):
        # type: (...) -> typing.Union[int, float]

        self.min_value = min_value
        self.max_value = max_value
        self.strict = strict

        super(NumberType, self).__init__(**kwargs)

    def _mock(self, context=None):
        number = random.uniform(
            *get_range_endpoints(self.min_value, self.max_value)
        )
        return self.native_type(number) if self.native_type else number
github schematics / schematics / schematics / types / base.py View on Github external
primitive_type = str
    native_type = datetime.datetime

    SERIALIZED_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'

    MESSAGES = {
        'parse': _('Could not parse {0}. Should be ISO 8601 or timestamp.'),
        'parse_formats': _('Could not parse {0}. Valid formats: {1}'),
        'parse_external': _('Could not parse {0}.'),
        'parse_tzd_require': _('Could not parse {0}. Time zone offset required.'),
        'parse_tzd_reject': _('Could not parse {0}. Time zone offset not allowed.'),
        'tzd_require': _('Could not convert {0}. Time zone required but not found.'),
        'tzd_reject': _('Could not convert {0}. Time zone offsets not allowed.'),
        'validate_tzd_require': _('Time zone information required but not found.'),
        'validate_tzd_reject': _('Time zone information not allowed.'),
        'validate_utc_none': _('Time zone must be UTC but was None.'),
        'validate_utc_wrong': _('Time zone must be UTC.'),
    }

    REGEX = re.compile(r"""
                (?P\d{4})-(?P\d\d)-(?P\d\d)(?:T|\ )
                (?P\d\d):(?P\d\d)
                (?::(?P\d\d)(?:(?:\.|,)(?P\d{1,6}))?)?
                (?:(?P(?P[+−-])(?P\d\d):?(?P\d\d)?)
                |(?PZ))?$""", re.X)

    TIMEDELTA_ZERO = datetime.timedelta(0)

    class fixed_timezone(datetime.tzinfo):
        def utcoffset(self, dt): return self.offset
        def fromutc(self, dt): return dt + self.offset
github schematics / schematics / schematics / types / base.py View on Github external
def to_native(self, value, context=None):
        """Make sure a MultilingualStringType value is a dict or None."""

        if not (value is None or isinstance(value, dict)):
            raise ConversionError(_('Value must be a dict or None'))

        return value
github schematics / schematics / schematics / types / compound.py View on Github external
def check_length(self, value, context):
        list_length = len(value) if value else 0

        if self.min_size is not None and list_length < self.min_size:
            message = ({
                True: _('Please provide at least %d item.'),
                False: _('Please provide at least %d items.'),
            }[self.min_size == 1]) % self.min_size
            raise ValidationError(message)

        if self.max_size is not None and list_length > self.max_size:
            message = ({
                True: _('Please provide no more than %d item.'),
                False: _('Please provide no more than %d items.'),
            }[self.max_size == 1]) % self.max_size
            raise ValidationError(message)
github schematics / schematics / schematics / types / base.py View on Github external
be used in conjunction with the ``convert_tz`` option unless you only care about local
        wall clock times. Default: ``False``
            * ``True``:  Discard the ``tzinfo`` components and make naive ``datetime`` objects instead.
            * ``False``: Preserve the ``tzinfo`` components if present.
    """

    primitive_type = str
    native_type = datetime.datetime

    SERIALIZED_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'

    MESSAGES = {
        'parse': _('Could not parse {0}. Should be ISO 8601 or timestamp.'),
        'parse_formats': _('Could not parse {0}. Valid formats: {1}'),
        'parse_external': _('Could not parse {0}.'),
        'parse_tzd_require': _('Could not parse {0}. Time zone offset required.'),
        'parse_tzd_reject': _('Could not parse {0}. Time zone offset not allowed.'),
        'tzd_require': _('Could not convert {0}. Time zone required but not found.'),
        'tzd_reject': _('Could not convert {0}. Time zone offsets not allowed.'),
        'validate_tzd_require': _('Time zone information required but not found.'),
        'validate_tzd_reject': _('Time zone information not allowed.'),
        'validate_utc_none': _('Time zone must be UTC but was None.'),
        'validate_utc_wrong': _('Time zone must be UTC.'),
    }

    REGEX = re.compile(r"""
                (?P\d{4})-(?P\d\d)-(?P\d\d)(?:T|\ )
                (?P\d\d):(?P\d\d)
                (?::(?P\d\d)(?:(?:\.|,)(?P\d{1,6}))?)?
                (?:(?P(?P[+−-])(?P\d\d):?(?P\d\d)?)
                |(?PZ))?$""", re.X)
github schematics / schematics / schematics / types / base.py View on Github external
def to_native(self, value, context=None):
        """Make sure that a geo-value is of type (x, y)
        """
        if not isinstance(value, (tuple, list, dict)):
            raise ConversionError(_('GeoPointType can only accept tuples, lists, or dicts'))
        elements = self._normalize(value)
        if not len(elements) == 2:
            raise ConversionError(_('Value must be a two-dimensional point'))
        if not all(isinstance(v, (float, int)) for v in elements):
            raise ConversionError(_('Both values in point must be float or int'))
        return value
github schematics / schematics / schematics / types / base.py View on Github external
if self.regex is not None and self.regex.match(value) is None:
            raise ValidationError(self.messages['regex'])


class NumberType(BaseType):

    """A generic number field.
    Converts to and validates against `number_type` parameter.
    """

    primitive_type = None
    native_type = None
    number_type = None
    MESSAGES = {
        'number_coerce': _("Value '{0}' is not {1}."),
        'number_min': _("{0} value should be greater than or equal to {1}."),
        'number_max': _("{0} value should be less than or equal to {1}."),
    }

    def __init__(self, min_value=None, max_value=None, strict=False, **kwargs):
        # type: (...) -> typing.Union[int, float]

        self.min_value = min_value
        self.max_value = max_value
        self.strict = strict

        super(NumberType, self).__init__(**kwargs)

    def _mock(self, context=None):
        number = random.uniform(
            *get_range_endpoints(self.min_value, self.max_value)
        )
github schematics / schematics / schematics / contrib / mongo.py View on Github external
from ..exceptions import ConversionError

__all__ = ['ObjectIdType']


class ObjectIdType(BaseType):

    """An field wrapper around MongoDB ObjectIds.  It is correct to say they're
    bson fields, but I am unaware of bson being used outside MongoDB.

    `auto_fill` is disabled by default for ObjectIdType's as they are
    typically obtained after a successful save to Mongo.
    """

    MESSAGES = {
        'convert': _("Couldn't interpret value as an ObjectId."),
    }

    def __init__(self, auto_fill=False, **kwargs):
        self.auto_fill = auto_fill
        super(ObjectIdType, self).__init__(**kwargs)

    def to_native(self, value, context=None):
        if not isinstance(value, bson.objectid.ObjectId):
            try:
                value = bson.objectid.ObjectId(str(value))
            except bson.objectid.InvalidId:
                raise ConversionError(self.messages['convert'])
        return value

    def to_primitive(self, value, context=None):
        return str(value)
github schematics / schematics / schematics / types / base.py View on Github external
* ``False``: Preserve the ``tzinfo`` components if present.
    """

    primitive_type = str
    native_type = datetime.datetime

    SERIALIZED_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'

    MESSAGES = {
        'parse': _('Could not parse {0}. Should be ISO 8601 or timestamp.'),
        'parse_formats': _('Could not parse {0}. Valid formats: {1}'),
        'parse_external': _('Could not parse {0}.'),
        'parse_tzd_require': _('Could not parse {0}. Time zone offset required.'),
        'parse_tzd_reject': _('Could not parse {0}. Time zone offset not allowed.'),
        'tzd_require': _('Could not convert {0}. Time zone required but not found.'),
        'tzd_reject': _('Could not convert {0}. Time zone offsets not allowed.'),
        'validate_tzd_require': _('Time zone information required but not found.'),
        'validate_tzd_reject': _('Time zone information not allowed.'),
        'validate_utc_none': _('Time zone must be UTC but was None.'),
        'validate_utc_wrong': _('Time zone must be UTC.'),
    }

    REGEX = re.compile(r"""
                (?P\d{4})-(?P\d\d)-(?P\d\d)(?:T|\ )
                (?P\d\d):(?P\d\d)
                (?::(?P\d\d)(?:(?:\.|,)(?P\d{1,6}))?)?
                (?:(?P(?P[+−-])(?P\d\d):?(?P\d\d)?)
                |(?PZ))?$""", re.X)

    TIMEDELTA_ZERO = datetime.timedelta(0)

    class fixed_timezone(datetime.tzinfo):