Python oslo_i18n.translate() Examples

The following are 22 code examples of oslo_i18n.translate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_i18n , or try the search function .
Example #1
Source File: api_common.py    From tacker with Apache License 2.0 6 votes vote down vote up
def translate(translatable, locale):
    """Translate the object to the given locale.

    If the object is an exception its translatable elements are translated
    in place, if the object is a translatable string it is translated and
    returned. Otherwise, the object is returned as-is.

    :param translatable: the object to be translated
    :param locale: the locale to translate to
    :returns: the translated object, or the object as-is if it
              was not translated
    """
    localize = oslo_i18n.translate
    if isinstance(translatable, exceptions.TackerException):
        translatable.msg = localize(translatable.msg, locale)
    elif isinstance(translatable, exc.HTTPError):
        translatable.detail = localize(translatable.detail, locale)
    elif isinstance(translatable, Exception):
        translatable.message = localize(translatable, locale)
    else:
        return localize(translatable, locale)
    return translatable 
Example #2
Source File: wsgi.py    From tacker with Apache License 2.0 5 votes vote down vote up
def __call__(self, req):
        """Generate a WSGI response based on the exception passed to ctor."""
        user_locale = req.best_match_language()
        # Replace the body with fault details.
        code = self.wrapped_exc.status_int
        fault_name = self._fault_names.get(code, "tackerFault")
        explanation = self.wrapped_exc.explanation
        LOG.debug("Returning %(code)s to user: %(explanation)s",
                  {'code': code, 'explanation': explanation})

        explanation = i18n.translate(explanation, user_locale)
        fault_data = {
            fault_name: {
                'code': code,
                'message': explanation}}
        if code == 413 or code == 429:
            retry = self.wrapped_exc.headers.get('Retry-After', None)
            if retry:
                fault_data[fault_name]['retryAfter'] = retry

        self.wrapped_exc.content_type = 'application/json'
        self.wrapped_exc.charset = 'UTF-8'

        body = JSONDictSerializer().serialize(fault_data)
        if isinstance(body, six.text_type):
            body = body.encode('utf-8')
        self.wrapped_exc.body = body

        return self.wrapped_exc 
Example #3
Source File: i18n.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale) 
Example #4
Source File: i18n.py    From karbor with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale) 
Example #5
Source File: i18n.py    From aodh with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #6
Source File: i18n.py    From coriolis with GNU Affero General Public License v3.0 5 votes vote down vote up
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale) 
Example #7
Source File: wsgi.py    From senlin with Apache License 2.0 5 votes vote down vote up
def translate_exception(ex, locale):
    """Translate all translatable elements of the given exception."""
    if isinstance(ex, exception.SenlinException):
        ex.message = oslo_i18n.translate(ex.message, locale)
    else:
        ex.message = oslo_i18n.translate(str(ex), locale)

    if isinstance(ex, exc.HTTPError):
        ex.explanation = oslo_i18n.translate(ex.explanation, locale)
        ex.detail = oslo_i18n.translate(getattr(ex, 'detail', ''), locale)
    return ex 
Example #8
Source File: i18n.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #9
Source File: i18n.py    From os-vif with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #10
Source File: versions.py    From tacker with Apache License 2.0 5 votes vote down vote up
def __call__(self, req):
        """Respond to a request for all Tacker API versions."""
        version_objs = [
            {
                "id": "v1.0",
                "status": "CURRENT",
            },
        ]

        if req.path != '/':
            language = req.best_match_language()
            msg = _('Unknown API version specified')
            msg = oslo_i18n.translate(msg, language)
            return webob.exc.HTTPNotFound(explanation=msg)

        builder = versions_view.get_view_builder(req)
        versions = [builder.build(version) for version in version_objs]
        response = dict(versions=versions)
        metadata = {}

        content_type = req.best_match_content_type()
        body = (wsgi.Serializer(metadata=metadata).
                serialize(response, content_type))

        response = webob.Response()
        response.content_type = content_type
        response.body = body

        return response 
Example #11
Source File: api_common.py    From tacker with Apache License 2.0 5 votes vote down vote up
def convert_exception_to_http_exc(e, faults, language):
    serializer = wsgi.JSONDictSerializer()
    e = translate(e, language)
    body = serializer.serialize(
        {'TackerError': get_exception_data(e)})
    kwargs = {'body': body, 'content_type': 'application/json'}
    if isinstance(e, exc.HTTPException):
        # already an HTTP error, just update with content type and body
        e.body = body
        e.content_type = kwargs['content_type']
        return e
    if isinstance(e, (exceptions.TackerException, netaddr.AddrFormatError,
                      oslo_policy.PolicyNotAuthorized)):
        for fault in faults:
            if isinstance(e, fault):
                mapped_exc = faults[fault]
                break
        else:
            mapped_exc = exc.HTTPInternalServerError
        return mapped_exc(**kwargs)
    if isinstance(e, NotImplementedError):
        # NOTE(armando-migliaccio): from a client standpoint
        # it makes sense to receive these errors, because
        # extensions may or may not be implemented by
        # the underlying plugin. So if something goes south,
        # because a plugin does not implement a feature,
        # returning 500 is definitely confusing.
        kwargs['body'] = serializer.serialize(
            {'NotImplementedError': get_exception_data(e)})
        return exc.HTTPNotImplemented(**kwargs)
    # NOTE(jkoelker) Everything else is 500
    # Do not expose details of 500 error to clients.
    msg = _('Request Failed: internal server error while '
            'processing your request.')
    msg = translate(msg, language)
    kwargs['body'] = serializer.serialize(
        {'TackerError': get_exception_data(exc.HTTPInternalServerError(msg))})
    return exc.HTTPInternalServerError(**kwargs) 
Example #12
Source File: test_public_api.py    From oslo.i18n with Apache License 2.0 5 votes vote down vote up
def test_translate(self):
        oslo_i18n.translate(u'string') 
Example #13
Source File: wsgi.py    From tacker with Apache License 2.0 5 votes vote down vote up
def _dispatch(req):
        """Dispatch a Request.

        Called by self._router after matching the incoming request to a route
        and putting the information into req.environ. Either returns 404
        or the routed WSGI app's response.
        """
        match = req.environ['wsgiorg.routing_args'][1]
        if not match:
            language = req.best_match_language()
            msg = _('The resource could not be found.')
            msg = i18n.translate(msg, language)
            return webob.exc.HTTPNotFound(explanation=msg)
        app = match['controller']
        return app 
Example #14
Source File: i18n.py    From vitrage with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #15
Source File: i18n.py    From masakari with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #16
Source File: _i18n.py    From syntribos with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #17
Source File: i18n.py    From manila with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #18
Source File: i18n.py    From magnum with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #19
Source File: _i18n.py    From Python-notes with MIT License 5 votes vote down vote up
def translate(msg, user_locale='zh_CN'):
    """
    翻译"msg"为指定的语言,默认"en_US"

    :param msg: the object to translate
    :param user_locale: the locale to translate the message to, if None the
                        default system locale will be used
                        'en_US' 'zh_CN'
    :returns: the translated object in unicode, or the original object if
              it could not be translated
    """
    return oslo_i18n.translate(msg, user_locale) 
Example #20
Source File: i18n.py    From vdi-broker with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale) 
Example #21
Source File: i18n.py    From compute-hyperv with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale) 
Example #22
Source File: i18n.py    From ec2-api with Apache License 2.0 5 votes vote down vote up
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale)