Deepak/Vinkesh | wrapped all messages under gettext for internationalization

This commit is contained in:
vinkesh banka
2011-08-04 16:55:34 +05:30
committed by Rajaram Mallya
parent 2a204a09c3
commit dc8f68e24d
8 changed files with 103 additions and 88 deletions

View File

@@ -15,14 +15,14 @@
# License for the specific language governing permissions and limitations
# under the License.
import wsgi
import routes
import re
import httplib2
import json
from webob.exc import HTTPForbidden
from gettext import gettext as _
from melange.common.utils import import_class, cached_property
from melange.common.utils import import_class
class AuthorizationMiddleware(wsgi.Middleware):
@@ -55,8 +55,8 @@ class TenantBasedAuth(object):
return True
match = self.tenant_scoped_url.match(request.path_info)
if match and tenant_id != match.group('tenant_id'):
raise HTTPForbidden("User with tenant id %s cannot access "
"this resource" % tenant_id)
raise HTTPForbidden(_("User with tenant id %s cannot access "
"this resource" % tenant_id))
return True
@@ -70,8 +70,8 @@ class RoleBasedAuth(object):
return True
match = self.mapper.match(request.path_info, request.environ)
if match and match['action'] in match['controller'].admin_actions:
raise HTTPForbidden("User with roles %s cannot access "
"admin actions" % ', '.join(roles))
raise HTTPForbidden(_("User with roles %s cannot access "
"admin actions" % ', '.join(roles)))
return True
@@ -94,5 +94,6 @@ class KeystoneClient(httplib2.Http):
res, body = self.request(self.url, "POST", headers=headers,
body=request_body)
if int(res.status) >= 400:
raise Exception("Error occured while retrieving token : %s" % body)
raise Exception(_("Error occured while retrieving token : %s"
% body))
return json.loads(body)['auth']['token']['id']

View File

@@ -19,6 +19,8 @@ import httplib
import socket
import urllib
from gettext import gettext as _
class Client(object):
@@ -52,5 +54,5 @@ class Client(object):
response = connection.getresponse()
return response
except (socket.error, IOError), e:
raise Exception("Unable to connect to "
"server. Got error: %s" % e)
raise Exception(_("Unable to connect to "
"server. Got error: %s" % e))

View File

@@ -27,6 +27,7 @@ import optparse
import os
import sys
from gettext import gettext as _
from paste import deploy
@@ -64,22 +65,22 @@ def add_common_options(parser):
:param parser: optparse.OptionParser
"""
help_text = "The following configuration options are common to "\
"all melange programs."
help_text = _("The following configuration options are common to "
"all melange programs.")
group = optparse.OptionGroup(parser, "Common Options", help_text)
group.add_option('-v', '--verbose', default=False, dest="verbose",
action="store_true",
help="Print more verbose output")
help=_("Print more verbose output"))
group.add_option('-d', '--debug', default=False, dest="debug",
action="store_true",
help="Print debugging output")
help=_("Print debugging output"))
group.add_option('--config-file', default=None, metavar="PATH",
help="Path to the config file to use. When not specified "
"(the default), we generally look at the first "
"argument specified to be a config file, and if "
"that is also missing, we search standard "
"directories for a config file.")
help=_("Path to the config file to use. When not "
"specified (the default), we generally look at the"
" first argument specified to be a config file,"
" and if that is also missing, we search standard "
"directories for a config file."))
parser.add_option_group(group)
@@ -90,26 +91,26 @@ def add_log_options(parser):
:param parser: optparse.OptionParser
"""
help_text = "The following configuration options are specific to logging "\
"functionality for this program."
help_text = _("The following configuration options are specific to "
"logging functionality for this program.")
group = optparse.OptionGroup(parser, "Logging Options", help_text)
group.add_option('--log-config', default=None, metavar="PATH",
help="If this option is specified, the logging "
help=_("If this option is specified, the logging "
"configuration file specified is used and overrides "
"any other logging options specified. Please see "
"the Python logging module documentation for "
"details on logging configuration files.")
"details on logging configuration files."))
group.add_option('--log-date-format', metavar="FORMAT",
default=DEFAULT_LOG_DATE_FORMAT,
help="Format string for %(asctime)s in log records. "
"Default: %default")
help=_("Format string for %(asctime)s in log records. "
"Default: %default"))
group.add_option('--log-file', default=None, metavar="PATH",
help="(Optional) Name of log file to output to. "
"If not set, logging will go to stdout.")
help=_("(Optional) Name of log file to output to. "
"If not set, logging will go to stdout."))
group.add_option("--log-dir", default=None,
help="(Optional) The directory to keep log files in "
"(will be prepended to --logfile)")
help=_("(Optional) The directory to keep log files in "
"(will be prepended to --logfile)"))
parser.add_option_group(group)
@@ -127,8 +128,8 @@ def setup_logging(options, conf):
logging.config.fileConfig(options['log_config'])
return
else:
raise RuntimeError("Unable to locate specified logging "
"config file: %s" % options['log_config'])
raise RuntimeError(_("Unable to locate specified logging "
"config file: %s" % options['log_config']))
# If either the CLI option or the conf value
# is True, we set to True
@@ -238,14 +239,14 @@ def load_paste_config(app_name, options, args):
"""
conf_file = find_config_file(options, args)
if not conf_file:
raise RuntimeError("Unable to locate any configuration file. "
"Cannot load application %s" % app_name)
raise RuntimeError(_("Unable to locate any configuration file. "
"Cannot load application %s" % app_name))
try:
conf = deploy.appconfig("config:%s" % conf_file, name=app_name)
return conf_file, conf
except Exception, e:
raise RuntimeError("Error trying to load config %s: %s"
% (conf_file, e))
except Exception, error:
raise RuntimeError(_("Error trying to load config %(conf_file)s:"
" %(error)s" % locals()))
def load_paste_app(app_name, options, args):
@@ -299,9 +300,9 @@ def load_paste_app(app_name, options, args):
logger.debug("*" * 80)
app = deploy.loadapp("config:%s" % conf_file, name=app_name)
except (LookupError, ImportError), e:
raise RuntimeError("Unable to load %(app_name)s from "
raise RuntimeError(_("Unable to load %(app_name)s from "
"configuration file %(conf_file)s."
"\nGot: %(e)r" % locals())
"\nGot: %(e)r" % locals()))
return conf, app
@@ -323,7 +324,7 @@ def get_option(options, option, **kwargs):
elif 'default' in kwargs:
return kwargs['default']
else:
raise KeyError("option '%s' not found" % option)
raise KeyError(_("option '%s' not found" % option))
class Config(object):

View File

@@ -21,13 +21,14 @@ Nova-type exceptions. SHOULD include dedicated exception logging.
"""
import logging
from gettext import gettext as _
class ProcessExecutionError(IOError):
def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None,
description=None):
if description is None:
description = "Unexpected error while running command."
description = _("Unexpected error while running command.")
if exit_code is None:
exit_code = '-'
message = "%s\nCommand: %s\nExit code: %s\nStdout: %r\nStderr: %r" % (
@@ -71,6 +72,10 @@ class Invalid(MelangeError):
pass
class InvalidContentType(Invalid):
message = _("Invalid content type %(content_type)s.")
class BadInputError(Exception):
"""Error resulting from a client sending bad input to a server"""
pass

View File

@@ -22,10 +22,10 @@ import routes
import logging
import webob.dec
import webob.exc
from gettext import gettext as _
from melange.common import exception
from melange.common import wsgi
from gettext import gettext as _
LOG = logging.getLogger('melange.common.extensions')
@@ -398,8 +398,8 @@ class ExtensionManager(object):
self._check_extension(ext)
if alias in self.extensions:
raise exception.MelangeError("Found duplicate extension: %s"
% alias)
raise exception.MelangeError(_("Found duplicate extension: %s"
% alias))
self.extensions[alias] = ext

View File

@@ -33,6 +33,7 @@ from webob import Response
from xml.dom import minidom
from webob.exc import (HTTPBadRequest, HTTPInternalServerError,
HTTPNotFound, HTTPError, HTTPNotAcceptable)
from gettext import gettext as _
from melange.common.exception import InvalidContentType
from melange.common.exception import MelangeError
@@ -59,7 +60,7 @@ class VersionedURLMap(object):
if req.url_version is None and req.accept_version is not None:
version = "/v" + req.accept_version
app = self.urlmap.get(
version, Fault(HTTPNotAcceptable("version not supported")))
version, Fault(HTTPNotAcceptable(_("version not supported"))))
else:
app = self.urlmap
@@ -118,7 +119,7 @@ class Request(webob.Request):
return type
LOG.debug("Wrong Content-Type: %s" % type)
raise webob.exc.HTTPUnsupportedMediaType(
"Content type %s not supported" % type)
_("Content type %s not supported" % type))
@cached_property
def accept_version(self):

View File

@@ -21,6 +21,7 @@ SQLAlchemy models for Melange data
import netaddr
from netaddr.strategy.ipv6 import ipv6_verbose
from netaddr import IPNetwork, IPAddress
from gettext import gettext as _
from datetime import timedelta
from melange.common.exception import MelangeError
@@ -92,9 +93,10 @@ class ModelBase(object):
try:
column_type(self[column_name])
except (TypeError, ValueError):
type_name = column_type.__name__
self._add_error(column_name,
"{0} should be of type {1}".format(
column_name, column_type.__name__))
_("%(column_name)s should be of type %(type_name)s"
% locals()))
def _validate(self):
pass
@@ -119,7 +121,8 @@ class ModelBase(object):
def _validate_presence_of(self, attribute_name):
if (self[attribute_name] in [None, ""]):
self._add_error(attribute_name,
"{0} should be present".format(attribute_name))
_("%(attribute_name)s should be present"
% locals()))
def _validate_existence_of(self, attribute, model_class, **conditions):
model_id = self[attribute]
@@ -127,8 +130,10 @@ class ModelBase(object):
if model_id is not None and model_class.get_by(**conditions) is None:
conditions_str = ", ".join(["{0} = {1}".format(key, repr(value))
for key, value in conditions.iteritems()])
self._add_error(attribute, "{0} with {1} doesn't "
"exist".format(model_class.__name__, conditions_str))
model_class_name = model_class.__name__
self._add_error(attribute,
_("%(model_class_name)s with %(conditions_str)s"
" doesn't exist" % locals()))
@classmethod
def find(cls, id):
@@ -142,7 +147,7 @@ class ModelBase(object):
def find_by(cls, **conditions):
model = cls.get_by(**conditions)
if model == None:
raise ModelNotFoundError("%s Not Found" % cls.__name__)
raise ModelNotFoundError(_("%s Not Found" % cls.__name__))
return model
@classmethod
@@ -212,8 +217,8 @@ class ModelBase(object):
def _validate_positive_integer(self, attribute_name):
if(utils.parse_int(self[attribute_name]) < 0):
self._add_error(attribute_name,
"{0} should be a positive "
"integer".format(attribute_name))
_("%s should be a positive integer"
% attribute_name))
def _add_error(self, attribute_name, error_message):
self.errors[attribute_name] = self.errors.get(attribute_name, [])
@@ -232,8 +237,8 @@ def ipv6_address_generator_factory(cidr, **kwargs):
if hasattr(ip_generator, "required_params") else []
missing_params = set(required_params) - set(kwargs.keys())
if missing_params:
raise DataMissingError("Required params are missing: {0}".\
format(', '.join(missing_params)))
raise DataMissingError(_("Required params are missing: %s"
% (', '.join(missing_params))))
return ip_generator(cidr, **kwargs)
@@ -320,9 +325,9 @@ class IpBlock(ModelBase):
def allocate_ip(self, port_id=None, address=None, **kwargs):
if self.subnets():
raise IpAllocationNotAllowedError(
"Non Leaf block can not allocate IPAddress")
_("Non Leaf block can not allocate IPAddress"))
if self.is_full:
raise NoMoreAddressesError("IpBlock is full")
raise NoMoreAddressesError(_("IpBlock is full"))
if address is None:
address = self._generate_ip_address(**kwargs)
@@ -331,7 +336,7 @@ class IpBlock(ModelBase):
if not address:
self.update(is_full=True)
raise NoMoreAddressesError("IpBlock is full")
raise NoMoreAddressesError(_("IpBlock is full"))
return IpAddress.create(address=address, port_id=port_id,
ip_block_id=self.id)
@@ -361,12 +366,12 @@ class IpBlock(ModelBase):
if not self.contains(address):
raise AddressDoesNotBelongError(
"Address does not belong to IpBlock")
_("Address does not belong to IpBlock"))
policy = self.policy()
if not IpBlock.allowed_by_policy(self, policy, address):
raise AddressDisallowedByPolicyError(
"Block policy does not allow this address")
_("Block policy does not allow this address"))
def contains(self, address):
return netaddr.IPAddress(address) in IPNetwork(self.cidr)
@@ -379,7 +384,7 @@ class IpBlock(ModelBase):
def find_allocated_ip(self, address):
ip_address = IpAddress.find_by(ip_block_id=self.id, address=address)
if ip_address == None:
raise ModelNotFoundError("IpAddress Not Found")
raise ModelNotFoundError(_("IpAddress Not Found"))
return ip_address
def deallocate_ip(self, address):
@@ -404,7 +409,7 @@ class IpBlock(ModelBase):
def _validate_cidr_format(self):
if not self._has_valid_cidr():
self._add_error('cidr', "cidr is invalid")
self._add_error('cidr', _("cidr is invalid"))
def _has_valid_cidr(self):
try:
@@ -417,12 +422,12 @@ class IpBlock(ModelBase):
parent = self.parent
if parent and IPNetwork(self.cidr) not in IPNetwork(parent.cidr):
self._add_error('cidr',
"cidr should be within parent block's cidr")
_("cidr should be within parent block's cidr"))
def _validate_type(self):
if not (self.type in self._allowed_types):
self._add_error('type', "type should be one among {0}".format(
", ".join(self._allowed_types)))
self._add_error('type', _("type should be one among %s" %
(", ".join(self._allowed_types))))
def _validate_cidr(self):
self._validate_cidr_format()
@@ -439,14 +444,14 @@ class IpBlock(ModelBase):
return
for block in IpBlock.find_all(type='public', parent_id=None):
if self != block and self._overlaps(block):
msg = "cidr overlaps with public block {0}".format(block.cidr)
msg = _("cidr overlaps with public block %s" % block.cidr)
self._add_error('cidr', msg)
break
def _validate_cidr_does_not_overlap_with_siblings(self):
for sibling in self.siblings():
if self._overlaps(sibling):
msg = "cidr overlaps with sibling {0}".format(sibling.cidr)
msg = _("cidr overlaps with sibling %s" % sibling.cidr)
self._add_error('cidr', msg)
break
@@ -463,31 +468,31 @@ class IpBlock(ModelBase):
def _validate_cidr_doesnt_overlap_with_networked_toplevel_blocks(self):
for block in self.networked_top_level_blocks():
if self._overlaps(block):
self._add_error('cidr', "cidr overlaps with block {0}"
" in same network".format(block.cidr))
self._add_error('cidr', _("cidr overlaps with block %s"
" in same network" % block.cidr))
break
def _validate_belongs_to_supernet_network(self):
if(self.parent and self.parent.network_id and
self.parent.network_id != self.network_id):
self._add_error('network_id',
"network_id should be same as that of parent")
_("network_id should be same as that of parent"))
def _validate_belongs_to_supernet_tenant(self):
if(self.parent and self.parent.tenant_id and
self.parent.tenant_id != self.tenant_id):
self._add_error('tenant_id',
"tenant_id should be same as that of parent")
_("tenant_id should be same as that of parent"))
def _validate_parent_is_subnettable(self):
if (self.parent and self.parent.addresses()):
msg = "parent is not subnettable since it has allocated ips"
msg = _("parent is not subnettable since it has allocated ips")
self._add_error('parent_id', msg)
def _validate_type_is_same_within_network(self):
block = IpBlock.get_by(network_id=self.network_id)
if(block and block.type != self.type):
self._add_error('type', "type should be same within a network")
self._add_error('type', _("type should be same within a network"))
def _validate(self):
self._validate_type()
@@ -533,8 +538,8 @@ class IpAddress(ModelBase):
def add_inside_locals(self, ip_addresses):
db_api.save_nat_relationships([
{"inside_global_address_id": self.id,
"inside_local_address_id": local_address.id}
{'inside_global_address_id': self.id,
'inside_local_address_id': local_address.id}
for local_address in ip_addresses])
def deallocate(self):
@@ -549,8 +554,8 @@ class IpAddress(ModelBase):
def add_inside_globals(self, ip_addresses):
return db_api.save_nat_relationships([
{"inside_global_address_id": global_address.id,
"inside_local_address_id": self.id}
{'inside_global_address_id': global_address.id,
'inside_local_address_id': self.id}
for global_address in ip_addresses])
def inside_locals(self, **kwargs):
@@ -653,7 +658,7 @@ class Network(ModelBase):
def find_by(cls, id, tenant_id=None):
ip_blocks = IpBlock.find_all(network_id=id, tenant_id=tenant_id).all()
if(len(ip_blocks) == 0):
raise ModelNotFoundError("Network {0} not found".format(id))
raise ModelNotFoundError(_("Network %s not found" % id))
return cls(id=id, ip_blocks=ip_blocks)
@classmethod
@@ -675,7 +680,7 @@ class Network(ModelBase):
for blocks in self._block_partitions()]
if not any(ips):
raise NoMoreAddressesError("ip blocks in this network are full")
raise NoMoreAddressesError(_("ip blocks in this network are full"))
return filter(None, ips)
@@ -710,49 +715,49 @@ def models():
class NoMoreAddressesError(MelangeError):
def _error_message(self):
return "no more addresses"
return _("no more addresses")
class DuplicateAddressError(MelangeError):
def _error_message(self):
return "Address is already allocated"
return _("Address is already allocated")
class AddressDoesNotBelongError(MelangeError):
def _error_message(self):
return "Address does not belong here"
return _("Address does not belong here")
class AddressLockedError(MelangeError):
def _error_message(self):
return "Address is locked"
return _("Address is locked")
class ModelNotFoundError(MelangeError):
def _error_message(self):
return "Not Found"
return _("Not Found")
class DataMissingError(MelangeError):
def _error_message(self):
return "Data Missing"
return _("Data Missing")
class AddressDisallowedByPolicyError(MelangeError):
def _error_message(self):
return "Policy does not allow this address"
return _("Policy does not allow this address")
class IpAllocationNotAllowedError(MelangeError):
def _error_message(self):
return "Ip Block can not allocate address"
return _("Ip Block can not allocate address")
class InvalidModelError(MelangeError):
@@ -762,7 +767,7 @@ class InvalidModelError(MelangeError):
super(InvalidModelError, self).__init__(message)
def __str__(self):
return "The following values are invalid: %s" % str(self.errors)
return _("The following values are invalid: %s" % str(self.errors))
def _error_message(self):
return str(self)

View File

@@ -1171,7 +1171,7 @@ class TestIpRange(BaseTest):
ip_range = IpRange(offset='spdoe', length=10)
self.assertFalse(ip_range.is_valid())
self.assertTrue('offset should be of type integer' in
self.assertIn('offset should be of type integer',
ip_range.errors['offset'])
def test_ip_range_length_is_an_integer(self):