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


Python i18n._函数代码示例

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


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

示例1: validate_integer

    def validate_integer(value, name, min_value=None, max_value=None):
        """Make sure that value is a valid integer, potentially within range.

        :param value: the value of the integer
        :param name: the name of the integer
        :param min_length: the min_length of the integer
        :param max_length: the max_length of the integer
        :returns: integer
        """
        try:
            value = int(value)
        except (TypeError, ValueError, UnicodeEncodeError):
            raise webob.exc.HTTPBadRequest(explanation=(
                _('%s must be an integer.') % name))

        if min_value is not None and value < min_value:
            raise webob.exc.HTTPBadRequest(
                explanation=(_('%(value_name)s must be >= %(min_value)d') %
                             {'value_name': name, 'min_value': min_value}))
        if max_value is not None and value > max_value:
            raise webob.exc.HTTPBadRequest(
                explanation=(_('%(value_name)s must be <= %(max_value)d') %
                             {'value_name': name, 'max_value': max_value}))

        return value
开发者ID:Bloomie,项目名称:smaug,代码行数:25,代码来源:wsgi.py

示例2: _checkpoints_get_all

    def _checkpoints_get_all(self, context, provider_id, marker=None,
                             limit=None, sort_keys=None, sort_dirs=None,
                             filters=None, offset=None):
        check_policy(context, 'checkpoint_get_all')

        if filters is None:
            filters = {}

        try:
            if limit is not None:
                limit = int(limit)
                if limit <= 0:
                    msg = _('limit param must be positive')
                    raise exception.InvalidInput(reason=msg)
        except ValueError:
            msg = _('limit param must be an integer')
            raise exception.InvalidInput(reason=msg)

        if filters:
            LOG.debug("Searching by: %s.", six.text_type(filters))

        checkpoints = self.protection_api.list_checkpoints(
            context, provider_id, marker, limit,
            sort_keys=sort_keys,
            sort_dirs=sort_dirs,
            filters=filters,
            offset=offset)

        LOG.info(_LI("Get all checkpoints completed successfully."))
        return checkpoints
开发者ID:WeAreFormalGroup,项目名称:smaug,代码行数:30,代码来源:providers.py

示例3: create

    def create(self, req, body):
        """Creates a new restore."""
        if not self.is_valid_body(body, 'restore'):
            raise exc.HTTPUnprocessableEntity()

        LOG.debug('Create restore request body: %s', body)
        context = req.environ['smaug.context']
        check_policy(context, 'create')
        restore = body['restore']
        LOG.debug('Create restore request : %s', restore)

        if not restore.get("provider_id"):
            msg = _("provider_id must be provided when creating "
                    "a restore.")
            raise exception.InvalidInput(reason=msg)

        if not restore.get("checkpoint_id"):
            msg = _("checkpoint_id must be provided when creating "
                    "a restore.")
            raise exception.InvalidInput(reason=msg)

        parameters = restore.get("parameters")
        if not isinstance(parameters, dict):
            msg = _("parameters must be a dict when creating"
                    " a restore.")
            raise exception.InvalidInput(reason=msg)

        restore_properties = {
            'project_id': context.project_id,
            'provider_id': restore.get('provider_id'),
            'checkpoint_id': restore.get('checkpoint_id'),
            'restore_target': restore.get('restore_target'),
            'parameters': jsonutils.dumps(parameters),
            'status': 'started',
        }

        restoreobj = objects.Restore(context=context,
                                     **restore_properties)
        restoreobj.create()
        LOG.debug('call restore RPC  : restoreobj:%s', restoreobj)

        # call restore rpc API of protection service
        result = self.protection_api.restore(context, restoreobj)
        if result is True:
            status_update = "success"
        else:
            status_update = "failed"
        # update the status of restore
        update_dict = {
            "status": status_update
        }

        check_policy(context, 'update', restoreobj)
        self._restore_update(context,
                             restoreobj.get("id"), update_dict)

        restoreobj.update(update_dict)
        retval = self._view_builder.detail(req, restoreobj)

        return retval
开发者ID:Bloomie,项目名称:smaug,代码行数:60,代码来源:restores.py

示例4: create_trigger

    def create_trigger(self, context, trigger):
        if trigger.type not in ['time']:
            msg = (_("Invalid trigger type:%s") % trigger.type)
            raise exception.InvalidInput(msg)

        if trigger.properties['format'] not in ['crontab']:
            msg = (_("Invalid trigger time format type"))
            raise exception.InvalidInput(msg)
开发者ID:Bloomie,项目名称:smaug,代码行数:8,代码来源:test_triggers.py

示例5: check_time_format

    def check_time_format(cls, pattern):
        if not pattern:
            msg = (_("The trigger pattern is None"))
            raise exception.InvalidInput(msg)

        try:
            croniter(pattern)
        except Exception:
            msg = (_("The trigger pattern(%s) is invalid") % pattern)
            raise exception.InvalidInput(msg)
开发者ID:TommyLike,项目名称:smaug,代码行数:10,代码来源:crontab_time.py

示例6: checkpoints_create

    def checkpoints_create(self, req, provider_id, body):
        """Creates a new checkpoint."""
        if not self.is_valid_body(body, 'checkpoint'):
            raise exc.HTTPUnprocessableEntity()

        context = req.environ['smaug.context']

        LOG.debug('Create checkpoint request '
                  'body: %s provider_id:%s', body, provider_id)

        check_policy(context, 'checkpoint_create')
        checkpoint = body['checkpoint']
        LOG.debug('Create checkpoint request checkpoint: %s',
                  checkpoint)

        if not provider_id:
            msg = _("provider_id must be provided when creating "
                    "a checkpoint.")
            raise exception.InvalidInput(reason=msg)

        plan_id = checkpoint.get("plan_id")

        if not plan_id:
            msg = _("plan_id must be provided when creating "
                    "a checkpoint.")
            raise exception.InvalidInput(reason=msg)

        if not uuidutils.is_uuid_like(plan_id):
            msg = _("Invalid plan id provided.")
            raise exc.HTTPBadRequest(explanation=msg)

        plan = objects.Plan.get_by_id(context, plan_id)
        if not plan:
            raise exception.PlanNotFound(plan_id=plan_id)

        checkpoint_properties = {
            'project_id': context.project_id,
            'status': 'protecting',
            'provider_id': provider_id,
            "protection_plan": {
                "id": plan.get("id"),
                "name": plan.get("name"),
                "resources": plan.get("resources"),
            }
        }
        checkpoint = self.protection_api.protect(context, plan)
        if checkpoint is not None:
            checkpoint_properties['id'] = checkpoint.get('checkpoint_id')
        else:
            msg = _("Get checkpoint failed.")
            raise exc.HTTPNotFound(explanation=msg)

        returnval = self._checkpoint_view_builder.detail(
            req, checkpoint_properties)
        return returnval
开发者ID:WeAreFormalGroup,项目名称:smaug,代码行数:55,代码来源:providers.py

示例7: _get_offset_param

def _get_offset_param(params):
    """Extract offset id from request's dictionary (defaults to 0) or fail."""
    try:
        offset = int(params.pop('offset', 0))
    except ValueError:
        msg = _('offset param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    if offset < 0:
        msg = _('offset param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)

    return offset
开发者ID:Bloomie,项目名称:smaug,代码行数:13,代码来源:common.py

示例8: action_peek_json

def action_peek_json(body):
    """Determine action to invoke."""

    try:
        decoded = jsonutils.loads(body)
    except ValueError:
        msg = _("cannot understand JSON")
        raise exception.MalformedRequestBody(reason=msg)

    # Make sure there's exactly one key...
    if len(decoded) != 1:
        msg = _("too many body keys")
        raise exception.MalformedRequestBody(reason=msg)

    # Return the action and the decoded body...
    return list(decoded.keys())[0]
开发者ID:Bloomie,项目名称:smaug,代码行数:16,代码来源:wsgi.py

示例9: delete

    def delete(self, req, id):
        """Delete a trigger."""

        LOG.debug('Delete trigger(%s) start', id)

        context = req.environ['smaug.context']
        trigger = self._get_trigger_by_id(context, id)

        check_policy(context, 'delete', trigger)

        try:
            operations = objects.ScheduledOperationList.get_by_filters(
                context, {"trigger_id": id}, limit=1)
        except Exception as ex:
            self._raise_unknown_exception(ex)

        if operations:
            msg = _("There are more than one scheduled operations binded "
                    "with this trigger, please delete them first")
            raise exc.HTTPMethodNotAllowed(explanation=msg)

        try:
            self.operationengine_api.delete_trigger(context, id)
        except exception.TriggerNotFound as ex:
            pass
        except (exception.DeleteTriggerNotAllowed,
                Exception) as ex:
            self._raise_unknown_exception(ex)

        trigger.destroy()
开发者ID:TommyLike,项目名称:smaug,代码行数:30,代码来源:triggers.py

示例10: delete_backup

    def delete_backup(self, cntxt, checkpoint, **kwargs):
        resource_node = kwargs.get("node")
        resource_id = resource_node.value.id

        bank_section = checkpoint.get_resource_bank_section(resource_id)
        cinder_client = self._cinder_client(cntxt)

        LOG.info(_("deleting volume backup, volume_id: %s."), resource_id)
        try:
            bank_section.update_object("status",
                                       constants.RESOURCE_STATUS_DELETING)
            resource_definition = bank_section.get_object("metadata")
            backup_id = resource_definition["backup_id"]
            cinder_client.backups.delete(backup_id)
            bank_section.delete_object("metadata", resource_definition)
            self.protection_resource_map[resource_id] = {
                "bank_section": bank_section,
                "backup_id": backup_id,
                "cinder_client": cinder_client,
                "operation": "delete"
            }
        except Exception as e:
            LOG.error(_LE("delete volume backup failed, volume_id: %s."),
                      resource_id)
            bank_section.update_object("status",
                                       constants.CHECKPOINT_STATUS_ERROR)

            raise exception.DeleteBackupFailed(
                reason=six.text_type(e),
                resource_id=resource_id,
                resource_type=constants.VOLUME_RESOURCE_TYPE
            )
开发者ID:eshedg,项目名称:smaug,代码行数:32,代码来源:cinder_protection_plugin.py

示例11: _sync_status

 def _sync_status(self, checkpoint, status_getters):
     status = {}
     for s in status_getters:
         resource_id = s.get('resource_id')
         get_resource_stats = s.get('get_resource_stats')
         status[resource_id] = get_resource_stats(checkpoint,
                                                  resource_id)
     if constants.RESOURCE_STATUS_ERROR in status.values():
         checkpoint.status = constants.CHECKPOINT_STATUS_ERROR
         checkpoint.commit()
     elif constants.RESOURCE_STATUS_PROTECTING in status.values():
         checkpoint.status = constants.CHECKPOINT_STATUS_PROTECTING
         checkpoint.commit()
     elif constants.RESOURCE_STATUS_UNDEFINED in status.values():
         checkpoint.status = constants.CHECKPOINT_STATUS_PROTECTING
         checkpoint.commit()
     else:
         checkpoint.status = constants.CHECKPOINT_STATUS_AVAILABLE
         checkpoint.commit()
         LOG.info(_("Stop sync checkpoint status,checkpoint_id:"
                    "%(checkpoint_id)s,checkpoint status:"
                    "%(checkpoint_status)s") %
                  {"checkpoint_id": checkpoint.id,
                   "checkpoint_status": checkpoint.status})
         raise loopingcall.LoopingCallDone()
开发者ID:paperandsoap,项目名称:smaug,代码行数:25,代码来源:create_protection.py

示例12: __call__

    def __call__(self, environ, start_response):
        """Subclasses will probably want to implement __call__ like this:

        @webob.dec.wsgify(RequestClass=Request)
        def __call__(self, req):
          # Any of the following objects work as responses:

          # Option 1: simple string
          res = 'message\n'

          # Option 2: a nicely formatted HTTP exception page
          res = exc.HTTPForbidden(explanation='Nice try')

          # Option 3: a webob Response object (in case you need to play with
          # headers, or you want to be treated like an iterable)
          res = Response();
          res.app_iter = open('somefile')

          # Option 4: any wsgi app to be run next
          res = self.application

          # Option 5: you can get a Response object for a wsgi app, too, to
          # play with headers etc
          res = req.get_response(self.application)

          # You can then just return your response...
          return res
          # ... or set req.response and return None.
          req.response = res

        See the end of http://pythonpaste.org/webob/modules/dec.html
        for more info.

        """
        raise NotImplementedError(_('You must implement __call__'))
开发者ID:Bloomie,项目名称:smaug,代码行数:35,代码来源:common.py

示例13: __init__

    def __init__(self, name, loader=None):
        """Initialize, but do not start the WSGI server.

        :param name: The name of the WSGI server given to the loader.
        :param loader: Loads the WSGI application using the given name.
        :returns: None

        """
        self.name = name
        self.manager = self._get_manager()
        self.loader = loader or wsgi_common.Loader()
        self.app = self.loader.load_app(name)
        self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0")
        self.port = getattr(CONF, '%s_listen_port' % name, 0)
        self.workers = (getattr(CONF, '%s_workers' % name, None) or
                        processutils.get_worker_count())
        if self.workers and self.workers < 1:
            worker_name = '%s_workers' % name
            msg = (_("%(worker_name)s value of %(workers)d is invalid, "
                     "must be greater than 0.") %
                   {'worker_name': worker_name,
                    'workers': self.workers})
            raise exception.InvalidInput(msg)

        self.server = wsgi.Server(name,
                                  self.app,
                                  host=self.host,
                                  port=self.port)
开发者ID:Bloomie,项目名称:smaug,代码行数:28,代码来源:service.py

示例14: model_query

def model_query(context, *args, **kwargs):
    """Query helper that accounts for context's `read_deleted` field.

    :param context: context to query under
    :param session: if present, the session to use
    :param read_deleted: if present, overrides context's read_deleted field.
    :param project_only: if present and context is user-type, then restrict
            query to match the context's project_id.
    """
    session = kwargs.get('session') or get_session()
    read_deleted = kwargs.get('read_deleted') or context.read_deleted
    project_only = kwargs.get('project_only')

    query = session.query(*args)
    if read_deleted == 'no':
        query = query.filter_by(deleted=False)
    elif read_deleted == 'yes':
        pass  # omit the filter to include deleted and active
    elif read_deleted == 'only':
        query = query.filter_by(deleted=True)
    else:
        raise Exception(
            _("Unrecognized read_deleted value '%s'") % read_deleted)

    if project_only and is_user_context(context):
        query = query.filter_by(project_id=context.project_id)

    return query
开发者ID:WeAreFormalGroup,项目名称:smaug,代码行数:28,代码来源:api.py

示例15: create_backup

    def create_backup(self, cntxt, checkpoint, **kwargs):
        resource_node = kwargs.get("node")
        image_id = resource_node.value.id
        bank_section = checkpoint.get_resource_bank_section(image_id)

        resource_definition = {"resource_id": image_id}
        glance_client = self._glance_client(cntxt)

        LOG.info(_("creating image backup, image_id: %s."), image_id)
        try:
            bank_section.create_object("status",
                                       constants.RESOURCE_STATUS_PROTECTING)
            image_info = glance_client.images.get(image_id)
            image_metadata = {
                "disk_format": image_info.disk_format,
                "container_format": image_info.container_format
            }
            resource_definition["image_metadata"] = image_metadata
            resource_definition["backup_id"] = image_id

            bank_section.create_object("metadata", resource_definition)
        except Exception as err:
            LOG.error(_LE("create image backup failed, image_id: %s."),
                      image_id)
            bank_section.update_object("status",
                                       constants.RESOURCE_STATUS_ERROR)
            raise exception.CreateBackupFailed(
                reason=err,
                resource_id=image_id,
                resource_type=constants.IMAGE_RESOURCE_TYPE)

        self._add_to_threadpool(self._create_backup, glance_client,
                                bank_section, image_id)
开发者ID:TommyLike,项目名称:smaug,代码行数:33,代码来源:image_protection_plugin.py


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