Example #1
0
def translate_exception(ex, locale):
    """Translates 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(six.text_type(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 #2
0
def translate_exception(exc, locale):
    """Translates all translatable elements of the given exception."""
    if isinstance(exc, exception.HeatException):
        exc.message = i18n.translate(exc.message, locale)
    else:
        exc.message = i18n.translate(six.text_type(exc), locale)

    if isinstance(exc, webob.exc.HTTPError):
        exc.explanation = i18n.translate(exc.explanation, locale)
        exc.detail = i18n.translate(getattr(exc, 'detail', ''), locale)
    return exc
Example #3
0
def translate_exception(exc, locale):
    """Translates all translatable elements of the given exception."""
    if isinstance(exc, exception.SenlinException):
        exc.message = oslo_i18n.translate(exc.message, locale)
    else:
        exc.message = oslo_i18n.translate(six.text_type(exc), locale)

    if isinstance(exc, webob.exc.HTTPError):
        exc.explanation = oslo_i18n.translate(exc.explanation, locale)
        exc.detail = oslo_i18n.translate(getattr(exc, 'detail', ''), locale)
    return exc
Example #4
0
def translate_exception(exc, locale):
    """Translates all translatable elements of the given exception."""
    if isinstance(exc, exception.HeatException):
        exc.message = i18n.translate(exc.message, locale)
    else:
        err_msg = encodeutils.exception_to_unicode(exc)
        exc.message = i18n.translate(err_msg, locale)

    if isinstance(exc, webob.exc.HTTPError):
        exc.explanation = i18n.translate(exc.explanation, locale)
        exc.detail = i18n.translate(getattr(exc, 'detail', ''), locale)
    return exc
Example #5
0
def translate_exception(exc, locale):
    """Translates all translatable elements of the given exception."""
    if isinstance(exc, exception.HeatException):
        exc.message = i18n.translate(exc.message, locale)
    else:
        err_msg = encodeutils.exception_to_unicode(exc)
        exc.message = i18n.translate(err_msg, locale)

    if isinstance(exc, webob.exc.HTTPError):
        exc.explanation = i18n.translate(exc.explanation, locale)
        exc.detail = i18n.translate(getattr(exc, 'detail', ''), locale)
    return exc
Example #6
0
    def __call__(self, req):
        """Respond to a request for all Neutron API versions."""
        version_objs = [
            {
                "id": "v2.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 = wsgi.encode_body(body)

        return response
Example #7
0
def render_exception(error, context=None, request=None, user_locale=None):
    """Form a WSGI response based on the current error."""
    error_message = error.args[0]
    message = oslo_i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {
        'error': {
            'code': error.code,
            'title': error.title,
            'message': message,
        }
    }
    headers = []
    if isinstance(error, exception.AuthPluginException):
        body['error']['identity'] = error.authentication
    elif isinstance(error, exception.Unauthorized):
        # NOTE(gyee): we only care about the request environment in the
        # context. Also, its OK to pass the environment as it is read-only in
        # Application.base_url()
        local_context = {}
        if request:
            local_context = {'environment': request.environ}
        elif context and 'environment' in context:
            local_context = {'environment': context['environment']}
        url = Application.base_url(local_context, 'public')

        headers.append(('WWW-Authenticate', 'Keystone uri="%s"' % url))
    return render_response(status=(error.code, error.title),
                           body=body,
                           headers=headers)
Example #8
0
    def __call__(self, req):
        """Respond to a request for all Neutron API versions."""
        version_objs = [
            {
                "id": "v2.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 #9
0
def render_exception(error, context=None, request=None, user_locale=None):
    """Form a WSGI response based on the current error."""
    error_message = error.args[0]
    message = oslo_i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {'error': {
        'code': error.code,
        'title': error.title,
        'message': message,
    }}
    headers = []
    if isinstance(error, exception.AuthPluginException):
        body['error']['identity'] = error.authentication
    elif isinstance(error, exception.Unauthorized):
        # NOTE(gyee): we only care about the request environment in the
        # context. Also, its OK to pass the environemt as it is read-only in
        # Application.base_url()
        local_context = {}
        if request:
            local_context = {'environment': request.environ}
        elif context and 'environment' in context:
            local_context = {'environment': context['environment']}
        url = Application.base_url(local_context, 'public')

        headers.append(('WWW-Authenticate', 'Keystone uri="%s"' % url))
    return render_response(status=(error.code, error.title),
                           body=body,
                           headers=headers)
Example #10
0
def render_exception(error, context=None, request=None, user_locale=None):
    """Forms a WSGI response based on the current error."""

    error_message = error.args[0]
    message = oslo_i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {"error": {"code": error.code, "title": error.title, "message": message}}
    headers = []
    if isinstance(error, exception.AuthPluginException):
        body["error"]["identity"] = error.authentication
    elif isinstance(error, exception.Unauthorized):
        url = CONF.public_endpoint
        if not url:
            if request:
                context = {"host_url": request.host_url}
            if context:
                url = Application.base_url(context, "public")
            else:
                url = "http://localhost:%d" % CONF.eventlet_server.public_port
        else:
            substitutions = dict(itertools.chain(six.iteritems(CONF), six.iteritems(CONF.eventlet_server)))
            url = url % substitutions

        headers.append(("WWW-Authenticate", 'Keystone uri="%s"' % url))
    return render_response(status=(error.code, error.title), body=body, headers=headers)
Example #11
0
    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, str):
            body = body.encode('utf-8')
        self.wrapped_exc.body = body

        return self.wrapped_exc
Example #12
0
def render_exception(error, context=None, request=None, user_locale=None):
    """Forms a WSGI response based on the current error."""
    error_message = error.args[0]
    message = oslo_i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {'error': {
        'code': error.code,
        'title': error.title,
        'message': message,
    }}
    headers = []
    if isinstance(error, exception.AuthPluginException):
        body['error']['identity'] = error.authentication
    elif isinstance(error, exception.Unauthorized):
        url = CONF.public_endpoint
        if not url:
            if request:
                context = {'host_url': request.host_url}
            if context:
                url = Application.base_url(context, 'public')
            else:
                url = 'http://localhost:%d' % CONF.eventlet_server.public_port
        else:
            substitutions = dict(
                itertools.chain(CONF.items(), CONF.eventlet_server.items()))
            url = url % substitutions

        headers.append(('WWW-Authenticate', 'Keystone uri="%s"' % url))
    return render_response(status=(error.code, error.title),
                           body=body,
                           headers=headers)
Example #13
0
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 #14
0
 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 #15
0
    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 = oslo_i18n.translate(msg, language)
            return webob.exc.HTTPNotFound(explanation=msg)
        app = match['controller']
        return app
Example #16
0
def render_exception(error, request=None, user_locale=None):
    """Forms a WSGI response based on the current error."""

    error_message = error.args[0]
    message = i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {'error': {
        'code': error.code,
        'title': error.title,
        'message': message,
    }}
    headers = []
    return render_response(status=(error.code, error.title),
                           body=body,
                           headers=headers)
Example #17
0
def render_exception(error, request=None, user_locale=None):
    """Forms a WSGI response based on the current error."""

    error_message = error.args[0]
    message = i18n.translate(error_message, desired_locale=user_locale)
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = six.text_type(message)

    body = {'error': {
        'code': error.code,
        'title': error.title,
        'message': message,
    }}
    headers = []
    return render_response(status=(error.code, error.title),
                           body=body,
                           headers=headers)
Example #18
0
def _handle_keystone_exception(error):
    # TODO(adriant): register this with its own specific handler:
    if isinstance(error, exception.InsufficientAuthMethods):
        return receipt_handlers.build_receipt(error)

    # Handle logging
    if isinstance(error, exception.Unauthorized):
        LOG.warning("Authorization failed. %(exception)s from %(remote_addr)s",
                    {
                        'exception': error,
                        'remote_addr': flask.request.remote_addr
                    })
    elif isinstance(error, exception.UnexpectedError):
        LOG.exception(str(error))
    else:
        LOG.warning(str(error))

    # Render the exception to something user "friendly"
    error_message = error.args[0]
    message = oslo_i18n.translate(error_message, _best_match_language())
    if message is error_message:
        # translate() didn't do anything because it wasn't a Message,
        # convert to a string.
        message = str(message)

    body = dict(error={
        'code': error.code,
        'title': error.title,
        'message': message
    })

    if isinstance(error, exception.AuthPluginException):
        body['error']['identity'] = error.authentication

    # Create the response and set status code.
    response = flask.jsonify(body)
    response.status_code = error.code

    # Add the appropriate WWW-Authenticate header for Unauthorized
    if isinstance(error, exception.Unauthorized):
        url = ks_flask.base_url()
        response.headers['WWW-Authenticate'] = 'Keystone uri="%s"' % url
    return response
Example #19
0
    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 = {
            "application/xml": {
                "attributes": {
                    "version": ["status", "id"],
                    "link": ["rel", "href"],
                }
            }
        }

        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 #20
0
File: i18n.py Project: kjylmr/guts
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale)
Example #21
0
 def test_translate(self):
     oslo_i18n.translate(u'string')
Example #22
0
def translate(value, user_locale=None):
    return i18n.translate(value, user_locale)
Example #23
0
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale)
Example #24
0
def translate(value, user_locale):
    return oslo_i18n.translate(value, user_locale)
Example #25
0
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical


def get_available_languages():
    return oslo_i18n.get_available_languages(DOMAIN)


print(get_available_languages())

import oslo_i18n

msg = "Message objects do not support addition."
trans_msg = oslo_i18n.translate(msg, 'zh_CN')

# *** no trying on i18n yet.
'''
Locale directory

    Python gettext looks for binary mo files for the given domain using the path 
    <localedir>/<language>/LC_MESSAGES/<domain>.mo. The default locale directory varies on distributions, 
    and it is /usr/share/locale in most cases.

    If you store message catalogs in a different location, you need to specify the location via an environment 
    variable named <DOMAIN>_LOCALEDIR where <DOMAIN> is an upper-case domain name with replacing _ and . with -. 
    For example, NEUTRON_LOCALEDIR for a domain neutron and OSLO_I18N_LOCALEDIR for a domain oslo_i18n.

'''
'''