当前位置: 首页>>代码示例>>Python>>正文


Python i18n._函数代码示例

本文整理汇总了Python中murano.common.i18n._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate_change

    def _validate_change(self, change):
        change_path = change['path'][0]
        change_op = change['op']
        allowed_methods = self.allowed_operations.get(change_path)

        if not allowed_methods:
            msg = _("Attribute '{0}' is invalid").format(change_path)
            raise webob.exc.HTTPForbidden(explanation=six.text_type(msg))

        if change_op not in allowed_methods:
            msg = _("Method '{method}' is not allowed for a path with name "
                    "'{name}'. Allowed operations are: "
                    "'{ops}'").format(method=change_op,
                                      name=change_path,
                                      ops=', '.join(allowed_methods))

            raise webob.exc.HTTPForbidden(explanation=six.text_type(msg))

        property_to_update = {change_path: change['value']}

        try:
            jsonschema.validate(property_to_update, schemas.PKG_UPDATE_SCHEMA)
        except jsonschema.ValidationError as e:
            LOG.error(_LE("Schema validation error occured: {error}")
                      .format(error=e))
            raise webob.exc.HTTPBadRequest(explanation=e.message)
开发者ID:Aqsamm,项目名称:murano,代码行数:26,代码来源:wsgi.py

示例2: update

    def update(self, request, environment_id, body):
        LOG.debug('Environments:Update <Id: {0}, '
                  'Body: {1}>'.format(environment_id, body))
        target = {"environment_id": environment_id}
        policy.check('update_environment', request.context, target)

        session = db_session.get_session()
        environment = session.query(models.Environment).get(environment_id)

        if environment is None:
            LOG.info(_LI('Environment <EnvId {0}> not '
                         'found').format(environment_id))
            raise exc.HTTPNotFound

        if environment.tenant_id != request.context.tenant:
            LOG.info(_LI('User is not authorized to access '
                         'this tenant resources.'))
            raise exc.HTTPUnauthorized

        LOG.debug('ENV NAME: {0}>'.format(body['name']))
        if VALID_NAME_REGEX.match(str(body['name'])):
            try:
                environment.update(body)
                environment.save(session)
            except db_exc.DBDuplicateEntry:
                msg = _('Environment with specified name already exists')
                LOG.exception(msg)
                raise exc.HTTPConflict(explanation=msg)
        else:
            msg = _('Environment name must contain only alphanumeric '
                    'or "_-." characters, must start with alpha')
            LOG.error(msg)
            raise exc.HTTPClientError(explanation=msg)

        return environment.to_dict()
开发者ID:aawm,项目名称:murano,代码行数:35,代码来源:environments.py

示例3: update

    def update(self, req, body, package_id):
        """List of allowed changes:
            { "op": "add", "path": "/tags", "value": [ "foo", "bar" ] }
            { "op": "add", "path": "/categories", "value": [ "foo", "bar" ] }
            { "op": "remove", "path": "/tags" }
            { "op": "remove", "path": "/categories" }
            { "op": "replace", "path": "/tags", "value": ["foo", "bar"] }
            { "op": "replace", "path": "/is_public", "value": true }
            { "op": "replace", "path": "/description",
                                "value":"New description" }
            { "op": "replace", "path": "/name", "value": "New name" }
        """
        policy.check("modify_package", req.context, {'package_id': package_id})

        pkg_to_update = db_api.package_get(package_id, req.context)
        if pkg_to_update.is_public:
            policy.check("manage_public_package", req.context)

        _check_content_type(req, 'application/murano-packages-json-patch')
        if not isinstance(body, list):
            msg = _('Request body must be a JSON array of operation objects.')
            LOG.error(msg)
            raise exc.HTTPBadRequest(explanation=msg)
        for change in body:
            if 'is_public' in change['path']:
                if change['value'] is True and not pkg_to_update.is_public:
                    policy.check('publicize_package', req.context)
            if 'name' in change['path']:
                if len(change['value']) > 80:
                    msg = _('Package name should be 80 characters maximum')
                    LOG.error(msg)
                    raise exc.HTTPBadRequest(explanation=msg)
        package = db_api.package_update(package_id, body, req.context)
        return package.to_dict()
开发者ID:GovardhanSN,项目名称:murano,代码行数:34,代码来源:catalog.py

示例4: _get_category_filters

 def _get_category_filters(req):
     query_params = {}
     valid_query_params = ['sort_keys', 'sort_dir', 'limit', 'marker']
     for key, value in req.GET.items():
         if key not in valid_query_params:
             raise exc.HTTPBadRequest(
                 _('Bad value passed to filter. '
                   'Got {key}, exected:{valid}').format(
                     key=key, valid=', '.join(valid_query_params)))
         if key == 'sort_keys':
             available_sort_keys = ['name', 'created',
                                    'updated', 'package_count', 'id']
             value = [v.strip() for v in value.split(',')]
             for sort_key in value:
                 if sort_key not in available_sort_keys:
                     raise exc.HTTPBadRequest(
                         explanation=_('Invalid sort key: {sort_key}. '
                                       'Must be one of the following: '
                                       '{available}').format(
                             sort_key=sort_key,
                             available=', '.join(available_sort_keys)))
         if key == 'sort_dir':
             if value not in ['asc', 'desc']:
                 msg = _('Invalid sort direction: {0}').format(value)
                 raise exc.HTTPBadRequest(explanation=msg)
         query_params[key] = value
     return query_params
开发者ID:abochkarev,项目名称:murano,代码行数:27,代码来源:catalog.py

示例5: create

 def create(self, request, body):
     """It creates the env template from the payload obtaining.
     This payload can contain just the template name, or include
     also service information.
     :param request: the operation request.
     :param body: the env template description
     :return: the description of the created template.
     """
     LOG.debug('EnvTemplates:Create <Body {body}>'.format(body=body))
     policy.check('create_env_template', request.context)
     try:
         LOG.debug('ENV TEMP NAME: {templ_name}>'.format(
             templ_name=body['name']))
         if not envs_api.VALID_NAME_REGEX.match(str(body['name'])):
             msg = _('Environment Template must contain only alphanumeric '
                     'or "_-." characters, must start with alpha')
             LOG.error(msg)
             raise exc.HTTPBadRequest(msg)
     except Exception:
             msg = _('Env template body is incorrect')
             LOG.exception(msg)
             raise exc.HTTPClientError(msg)
     if len(body['name']) > 255:
         msg = _('Environment Template name should be 255 characters '
                 'maximum')
         LOG.exception(msg)
         raise exc.HTTPBadRequest(explanation=msg)
     try:
         template = env_temps.EnvTemplateServices.create(
             body.copy(), request.context.tenant)
         return template.to_dict()
     except db_exc.DBDuplicateEntry:
         msg = _('Env Template with specified name already exists')
         LOG.exception(msg)
         raise exc.HTTPConflict(msg)
开发者ID:NikolayStarodubtsev,项目名称:murano,代码行数:35,代码来源:templates.py

示例6: update

    def update(self, request, env_template_id, body):
        """It updates the description template

        :param request: the operation request.
        :param env_template_id: the env template ID.
        :param body: the description to be updated
        :return: the updated template description.
        """
        LOG.debug('Templates:Update <Id: {templ_id}, '
                  'Body: {body}>'.format(templ_id=env_template_id, body=body))
        target = {"env_template_id": env_template_id}
        policy.check('update_env_template', request.context, target)

        self._validate_request(request, env_template_id)
        try:
            LOG.debug('ENV TEMP NAME: {temp_name}>'.format(
                temp_name=body['name']))
            if not str(body['name']).strip():
                msg = _('Environment Template must contain at least one '
                        'non-white space symbol')
                LOG.exception(msg)
                raise exc.HTTPBadRequest(msg)
        except Exception:
                msg = _('EnvTemplate body is incorrect')
                LOG.exception(msg)
                raise exc.HTTPBadRequest(msg)

        template = env_temps.EnvTemplateServices.update(env_template_id, body)
        return template.to_dict()
开发者ID:AleptNamrata,项目名称:murano,代码行数:29,代码来源:templates.py

示例7: _load_image

    def _load_image(self, file_name, default_name, what_image):
        full_path = os.path.join(
            self._source_directory, file_name or default_name)
        if not os.path.isfile(full_path) and not file_name:
            return

        allowed_ftype = ('png', 'jpeg', 'gif')
        allowed_size = 500 * 1024
        try:

            if imghdr.what(full_path) not in allowed_ftype:
                msg = _('{0}: Unsupported Format. Only {1} allowed').format(
                    what_image, ', '.join(allowed_ftype))

                raise exceptions.PackageLoadError(msg)

            fsize = os.stat(full_path).st_size
            if fsize > allowed_size:
                msg = _('{0}: Uploaded image size {1} is too large. '
                        'Max allowed size is {2}').format(
                    what_image, fsize, allowed_size)
                raise exceptions.PackageLoadError(msg)

            with open(full_path, 'rb') as stream:
                return stream.read()

        except Exception as ex:
            trace = sys.exc_info()[2]
            six.reraise(exceptions.PackageLoadError,
                        exceptions.PackageLoadError(
                            'Unable to load {0}: {1}'.format(what_image, ex)),
                        trace)
开发者ID:AleptNamrata,项目名称:murano,代码行数:32,代码来源:package_base.py

示例8: delete

    def delete(self, request, environment_id, session_id):
        LOG.debug('Session:Delete <SessionId: {0}>'.format(session_id))

        unit = db_session.get_session()
        session = unit.query(models.Session).get(session_id)

        self._check_session(request, environment_id, session, session_id)

        user_id = request.context.user
        if session.user_id != user_id:
            msg = _('User <UserId {0}> is not authorized to access session'
                    '<SessionId {1}>.').format(user_id, session_id)
            LOG.error(msg)
            raise exc.HTTPUnauthorized(explanation=msg)

        if session.state == states.SessionState.DEPLOYING:
            msg = _('Session <SessionId: {0}> is in deploying state and '
                    'could not be deleted').format(session_id)
            LOG.error(msg)
            raise exc.HTTPForbidden(explanation=msg)

        with unit.begin():
            unit.delete(session)

        return None
开发者ID:aawm,项目名称:murano,代码行数:25,代码来源:sessions.py

示例9: show

    def show(self, request, environment_id, session_id):
        LOG.debug('Session:Show <SessionId: {id}>'.format(id=session_id))

        unit = db_session.get_session()
        session = unit.query(models.Session).get(session_id)

        check_session(request, environment_id, session, session_id)

        user_id = request.context.user

        if session.user_id != user_id:
            msg = _('User <UserId {usr_id}> is not authorized to access'
                    'session <SessionId {s_id}>.').format(usr_id=user_id,
                                                          s_id=session_id)
            LOG.error(msg)
            raise exc.HTTPUnauthorized(explanation=msg)

        if not sessions.SessionServices.validate(session):
            msg = _('Session <SessionId {0}> is invalid: environment has been'
                    ' updated or updating right now with other session'
                    ).format(session_id)
            LOG.error(msg)
            raise exc.HTTPForbidden(explanation=msg)

        return session.to_dict()
开发者ID:NikolayStarodubtsev,项目名称:murano,代码行数:25,代码来源:sessions.py

示例10: __inner

    def __inner(self, request, *args, **kwargs):
        if hasattr(request, 'context') and not request.context.session:
            msg = _('X-Configuration-Session header which indicates'
                    ' to the session is missed')
            LOG.error(msg)
            raise exc.HTTPBadRequest(explanation=msg)

        session_id = request.context.session

        unit = db_session.get_session()
        session = unit.query(models.Session).get(session_id)

        if session is None:
            msg = _('Session <SessionId {0}> is not found').format(session_id)
            LOG.error(msg)
            raise exc.HTTPNotFound(explanation=msg)

        if not sessions.SessionServices.validate(session):
            msg = _('Session <SessionId {0}> '
                    'is invalid: environment has been updated or '
                    'updating right now with other session').format(session_id)
            LOG.error(msg)
            raise exc.HTTPForbidden(explanation=msg)

        if session.state == states.SessionState.DEPLOYING:
            msg = _('Session <SessionId {0}> is already in deployment state'
                    ).format(session_id)
            raise exc.HTTPForbidden(explanation=msg)
        return func(self, request, *args, **kwargs)
开发者ID:NikolayStarodubtsev,项目名称:murano,代码行数:29,代码来源:utils.py

示例11: upload

    def upload(self, req, body=None):
        """Upload new file archive for the new package
           together with package metadata.
        """
        policy.check("upload_package", req.context)

        _check_content_type(req, 'multipart/form-data')
        file_obj, package_meta = _validate_body(body)
        if package_meta:
            try:
                jsonschema.validate(package_meta, schemas.PKG_UPLOAD_SCHEMA)
            except jsonschema.ValidationError as e:
                msg = _("Package schema is not valid: {reason}").format(
                    reason=e)
                LOG.exception(msg)
                raise exc.HTTPBadRequest(explanation=msg)
        else:
            package_meta = {}

        if package_meta.get('is_public'):
            policy.check('publicize_package', req.context)

        with tempfile.NamedTemporaryFile(delete=False) as tempf:
            LOG.debug("Storing package archive in a temporary file")
            content = file_obj.file.read()
            if not content:
                msg = _("Uploading file can't be empty")
                LOG.error(msg)
                raise exc.HTTPBadRequest(explanation=msg)
            tempf.write(content)
            package_meta['archive'] = content
        try:
            with load_utils.load_from_file(
                    tempf.name, target_dir=None,
                    drop_dir=True) as pkg_to_upload:
                # extend dictionary for update db
                for k, v in six.iteritems(PKG_PARAMS_MAP):
                    if hasattr(pkg_to_upload, k):
                        package_meta[v] = getattr(pkg_to_upload, k)
                if len(package_meta['name']) > 80:
                    msg = _('Package name should be 80 characters maximum')
                    LOG.error(msg)
                    raise exc.HTTPBadRequest(explanation=msg)
                try:
                    package = db_api.package_upload(
                        package_meta, req.context.tenant)
                except db_exc.DBDuplicateEntry:
                    msg = _('Package with specified full '
                            'name is already registered')
                    LOG.exception(msg)
                    raise exc.HTTPConflict(msg)
                return package.to_dict()
        except pkg_exc.PackageLoadError as e:
            msg = _("Couldn't load package from file: {reason}").format(
                reason=e)
            LOG.exception(msg)
            raise exc.HTTPBadRequest(explanation=msg)
        finally:
            LOG.debug("Deleting package archive temporary file")
            os.remove(tempf.name)
开发者ID:GovardhanSN,项目名称:murano,代码行数:60,代码来源:catalog.py

示例12: update

    def update(self, request, env_template_id, body):
        """It updates the description template.
        :param request: the operation request.
        :param env_template_id: the env template ID.
        :param body: the description to be updated
        :return: the updated template description.
        """
        LOG.debug('Templates:Update <Id: {templ_id}, '
                  'Body: {body}>'.format(templ_id=env_template_id, body=body))
        target = {"env_template_id": env_template_id}
        policy.check('update_env_template', request.context, target)

        self._validate_request(request, env_template_id)
        try:
            LOG.debug('ENV TEMP NAME: {temp_name}>'.format(
                temp_name=body['name']))
            if not envs_api.VALID_NAME_REGEX.match(str(body['name'])):
                msg = _('Env Template must contain only alphanumeric '
                        'or "_-." characters, must start with alpha')
                LOG.exception(msg)
                raise exc.HTTPBadRequest(msg)
        except Exception:
                msg = _('EnvTemplate body is incorrect')
                LOG.exception(msg)
                raise exc.HTTPBadRequest(msg)

        template = env_temps.EnvTemplateServices.update(env_template_id, body)
        return template.to_dict()
开发者ID:NikolayStarodubtsev,项目名称:murano,代码行数:28,代码来源:templates.py

示例13: __call__

    def __call__(self, request):
        """WSGI method that controls (de)serialization and method dispatch."""

        LOG.debug("{method} {url}\nHEADERS: {headers}".format(
                  method=request.method,
                  url=request.url,
                  headers=self._format_request_headers(request.headers)))

        try:
            action, action_args, accept = self.deserialize_request(request)
        except exceptions.UnsupportedContentType:
            msg = _("Unsupported Content-Type")
            return webob.exc.HTTPUnsupportedMediaType(detail=msg)
        except exceptions.NotAcceptableContentType:
            msg = _("Acceptable response can not be provided")
            return webob.exc.HTTPNotAcceptable(detail=msg)
        except exceptions.MalformedRequestBody:
            msg = _("Malformed request body")
            return webob.exc.HTTPBadRequest(explanation=msg)

        with ResourceExceptionHandler():
            action_result = self.execute_action(action, request, **action_args)

        try:
            return self.serialize_response(action, action_result, accept)
        # return unserializable result (typically a webob exc)
        except Exception:
            return action_result
开发者ID:Aqsamm,项目名称:murano,代码行数:28,代码来源:wsgi.py

示例14: _load_package

 def _load_package(self, pkg_loader, name):
     try:
         parts = name.rsplit('/')
         if len(parts) == 2:
             name, pkg_version = parts
             version_spec = helpers.parse_version_spec(pkg_version)
         else:
             version_spec = helpers.parse_version_spec('*')
         package = pkg_loader.load_package(name, version_spec)
     except exceptions.NoPackageFound:
         if not CONF.packages_opts.load_packages_from:
             msg = _('Local package is not found since "load-packages-from"'
                     ' engine parameter is not provided and specified '
                     'packages is not loaded to murano-api')
         else:
             msg = _('Specified package is not found: {0} were scanned '
                     'together with murano database'
                     ).format(','.join(
                         CONF.packages_opts.load_packages_from))
         LOG.error(msg)
         self.error(msg, show_help=False)
     except exc.CommunicationError:
         msg = ('Murano API is not running. '
                'Check configuration parameters.')
         LOG.error(msg)
         self.error(msg, show_help=False)
     return package
开发者ID:GovardhanSN,项目名称:murano,代码行数:27,代码来源:test_runner.py

示例15: update

    def update(self, request, environment_id, body):
        LOG.debug('Environments:Update <Id: {id}, '
                  'Body: {body}>'.format(id=environment_id, body=body))
        target = {"environment_id": environment_id}
        policy.check('update_environment', request.context, target)

        session = db_session.get_session()
        environment = session.query(models.Environment).get(environment_id)
        new_name = six.text_type(body['name'])
        if new_name.strip():
            if len(new_name) > 255:
                msg = _('Environment name should be 255 characters maximum')
                LOG.error(msg)
                raise exc.HTTPBadRequest(explanation=msg)
            try:
                environment.update(body)
                environment.save(session)
            except db_exc.DBDuplicateEntry:
                msg = _('Environment with specified name already exists')
                LOG.error(msg)
                raise exc.HTTPConflict(explanation=msg)
        else:
            msg = _('Environment name must contain at least one '
                    'non-white space symbol')
            LOG.error(msg)
            raise exc.HTTPClientError(explanation=msg)

        return environment.to_dict()
开发者ID:AleptNamrata,项目名称:murano,代码行数:28,代码来源:environments.py


注:本文中的murano.common.i18n._函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。