• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python i18n._函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: delete

    def delete(self, _id):
        context = t_context.extract_context_from_environ()

        # TODO(joehuang): get the release of top and bottom
        t_release = 'MITATA'
        b_release = 'MITATA'

        s_ctx = self._get_res_routing_ref(context, _id, request.url)
        if not s_ctx:
            return Response(_('Failed to find resource'), 404)

        if s_ctx['b_url'] == '':
            return Response(_('bottom pod endpoint incorrect'), 404)

        b_headers = self._convert_header(t_release,
                                         b_release,
                                         request.headers)

        resp = hclient.forward_req(context, 'DELETE',
                                   b_headers,
                                   s_ctx['b_url'],
                                   request.body)

        response.status = resp.status_code

        # don't remove the resource routing for delete is async. operation
        # remove the routing when query is executed but not find

        # No content in the resp actually
        return {}
开发者ID:Ronghui,项目名称:tricircle,代码行数:30,代码来源:volume.py


示例2: check_string_length

def check_string_length(value, name=None, min_len=0, max_len=None):
    """Check the length of specified string

    :param value: the value of the string
    :param name: the name of the string
    :param min_len: the minimum length of the string
    :param max_len: the maximum length of the string

    """
    if not isinstance(value, six.string_types):
        if name is None:
            msg = _("The input is not a string or unicode")
        else:
            msg = _("%s is not a string or unicode") % name
        raise t_exceptions.InvalidInput(message=msg)

    if name is None:
        name = value

    if len(value) < min_len:
        msg = _("%(name)s has a minimum character requirement of "
                "%(min_length)s.") % {'name': name, 'min_length': min_len}
        raise t_exceptions.InvalidInput(message=msg)

    if max_len and len(value) > max_len:
        msg = _("%(name)s has more than %(max_length)s "
                "characters.") % {'name': name, 'max_length': max_len}
        raise t_exceptions.InvalidInput(message=msg)
开发者ID:dingboopt,项目名称:tricircle,代码行数:28,代码来源:utils.py


示例3: post

    def post(self, **kw):
        context = t_context.extract_context_from_environ()

        if not t_context.is_admin_context(context):
            pecan.abort(400, _('Admin role required to create bindings'))
            return

        if 'pod_binding' not in kw:
            pecan.abort(400, _('Request body not found'))
            return

        pod_b = kw['pod_binding']
        tenant_id = pod_b.get('tenant_id', '').strip()
        pod_id = pod_b.get('pod_id', '').strip()
        _uuid = uuidutils.generate_uuid()

        if tenant_id == '' or pod_id == '':
            return Response(
                _('Tenant_id and pod_id can not be empty'),
                422)

        # the az_pod_map_id should be exist for in the pod map table
        try:
            with context.session.begin():
                pod = core.get_resource(context, models.Pod,
                                        pod_id)
                if pod.get('az_name') == '':
                    return Response(_('Top region can not be bound'), 422)
        except t_exc.ResourceNotFound:
            return Response(_('pod_id not found in pod'), 422)
        except Exception as e:
            LOG.error(_LE('Fail to create pod binding: %(exception)s'),
                      {'exception': e})
            pecan.abort(500, _('Fail to create pod binding'))
            return

        try:
            with context.session.begin():
                pod_binding = core.create_resource(context, models.PodBinding,
                                                   {'id': _uuid,
                                                    'tenant_id': tenant_id,
                                                    'pod_id': pod_id})
        except db_exc.DBDuplicateEntry:
            return Response(_('Pod binding already exists'), 409)
        except db_exc.DBConstraintError:
            return Response(_('pod_id not exists in pod'), 422)
        except db_exc.DBReferenceError:
            return Response(_('DB reference not exists in pod'), 422)
        except Exception as e:
            LOG.error(_LE('Fail to create pod binding: %(exception)s'),
                      {'exception': e})
            pecan.abort(500, _('Fail to create pod binding'))
            return

        return {'pod_binding': pod_binding}
开发者ID:Ronghui,项目名称:tricircle,代码行数:55,代码来源:pod.py


示例4: get_one

    def get_one(self, _id):
        context = t_context.extract_context_from_environ()

        if _id == 'detail':
            return {'volumes': self._get_all(context)}

        # TODO(joehuang): get the release of top and bottom
        t_release = 'MITATA'
        b_release = 'MITATA'

        b_headers = self._convert_header(t_release,
                                         b_release,
                                         request.headers)

        s_ctx = self._get_res_routing_ref(context, _id, request.url)
        if not s_ctx:
            return Response(_('Failed to find resource'), 404)

        if s_ctx['b_url'] == '':
            return Response(_('bottom pod endpoint incorrect'), 404)

        resp = hclient.forward_req(context, 'GET',
                                   b_headers,
                                   s_ctx['b_url'],
                                   request.body)

        b_ret_body = jsonutils.loads(resp.content)

        b_status = resp.status_code
        response.status = b_status
        if b_status == 200:
            if b_ret_body.get('volume') is not None:
                b_vol_ret = b_ret_body['volume']
                ret_vol = self._convert_object(b_release, t_release,
                                               b_vol_ret,
                                               res_type=cons.RT_VOLUME)

                pod = self._get_pod_by_top_id(context, _id)
                if pod:
                    ret_vol['availability_zone'] = pod['az_name']

                return {'volume': ret_vol}

        # resource not find but routing exist, remove the routing
        if b_status == 404:
            filters = [{'key': 'top_id', 'comparator': 'eq', 'value': _id},
                       {'key': 'resource_type',
                        'comparator': 'eq',
                        'value': cons.RT_VOLUME}]
            with context.session.begin():
                core.delete_resources(context,
                                      models.ResourceRouting,
                                      filters)
        return b_ret_body
开发者ID:Ronghui,项目名称:tricircle,代码行数:54,代码来源:volume.py


示例5: get_one

    def get_one(self, _id):
        context = t_context.extract_context_from_environ()

        if not t_context.is_admin_context(context):
            pecan.abort(400, _('Admin role required to show pods'))
            return

        try:
            return {'pod': db_api.get_pod(context, _id)}
        except t_exc.ResourceNotFound:
            pecan.abort(404, _('Pod not found'))
            return
开发者ID:Ronghui,项目名称:tricircle,代码行数:12,代码来源:pod.py


示例6: delete

    def delete(self, _id):
        context = t_context.extract_context_from_environ()

        if not t_context.is_admin_context(context):
            pecan.abort(400, _('Admin role required to delete bindings'))
            return

        try:
            with context.session.begin():
                core.delete_resource(context, models.PodBinding, _id)
                pecan.response.status = 200
        except t_exc.ResourceNotFound:
            pecan.abort(404, _('Pod binding not found'))
            return
开发者ID:Ronghui,项目名称:tricircle,代码行数:14,代码来源:pod.py


示例7: get_all

    def get_all(self):
        context = t_context.extract_context_from_environ()

        if not t_context.is_admin_context(context):
            pecan.abort(400, _('Admin role required to list pods'))
            return

        try:
            return {'pods': db_api.list_pods(context)}
        except Exception as e:
            LOG.error(_LE('Fail to list pod: %(exception)s'),
                      {'exception': e})
            pecan.abort(500, _('Fail to list pod'))
            return
开发者ID:Ronghui,项目名称:tricircle,代码行数:14,代码来源:pod.py


示例8: put

    def put(self, _id, **kw):
        context = t_context.extract_context_from_environ()

        if not policy.enforce(context, policy.ADMIN_API_ROUTINGS_PUT):
            return utils.format_api_error(
                403, _('Unauthorized to update resource routing'))

        try:
            db_api.get_resource_routing(context, _id)
        except t_exceptions.ResourceNotFound:
            return utils.format_api_error(404,
                                          _('Resource routing not found'))

        if 'routing' not in kw:
            return utils.format_api_error(
                400, _('Request body not found'))

        update_dict = kw['routing']

        # values to be updated should not be empty
        for field in update_dict:
            value = update_dict.get(field)
            if value is None or len(value.strip()) == 0:
                return utils.format_api_error(
                    400, _("Field %(field)s can not be empty") % {
                        'field': field})

        # the resource type should be properly provisioned.
        if 'resource_type' in update_dict:
            if not constants.is_valid_resource_type(
                    update_dict['resource_type']):
                return utils.format_api_error(
                    400, _('There is no such resource type'))

        # the pod with new pod_id should exist in pod table
        if 'pod_id' in update_dict:
            new_pod_id = update_dict.get('pod_id')
            try:
                # find the pod through the pod_id and verify whether it exists
                db_api.get_pod(context, new_pod_id)
            except t_exceptions.ResourceNotFound:
                return utils.format_api_error(
                    400, _("The pod %(new_pod_id)s doesn't"
                           " exist") % {'new_pod_id': new_pod_id})
            except Exception as e:
                LOG.exception('Failed to update resource routing: '
                              '%(exception)s ', {'exception': e})
                return utils.format_api_error(
                    500, _('Failed to update resource routing'))

        try:
            routing_updated = db_api.update_resource_routing(
                context, _id, update_dict)
            return {'routing': routing_updated}
        except Exception as e:
            LOG.exception('Failed to update resource routing: '
                          '%(exception)s ', {'exception': e})
            return utils.format_api_error(
                500, _('Failed to update resource routing'))
开发者ID:LongXQ,项目名称:tricircle,代码行数:59,代码来源:routing.py


示例9: bool_from_string

def bool_from_string(subject, strict=False, default=False):
    """Interpret a string as a boolean.

    A case-insensitive match is performed such that strings matching 't',
    'true', 'on', 'y', 'yes', or '1' are considered True and, when
    `strict=False`, anything else returns the value specified by 'default'.
    Useful for JSON-decoded stuff and config file parsing.
    If `strict=True`, unrecognized values, including None, will raise a
    ValueError which is useful when parsing values passed in from an API call.
    Strings yielding False are 'f', 'false', 'off', 'n', 'no', or '0'.
    """

    if not isinstance(subject, six.string_types):
        subject = six.text_type(subject)

    lowered = subject.strip().lower()

    if lowered in TRUE_STRINGS:
        return True
    elif lowered in FALSE_STRINGS:
        return False
    elif strict:
        acceptable = ', '.join(
            "'%s'" % s for s in sorted(TRUE_STRINGS + FALSE_STRINGS))
        msg = _("Unrecognized value '%(val)s', acceptable values are:"
                " %(acceptable)s") % {'val': subject,
                                      'acceptable': acceptable}
        raise ValueError(msg)
    else:
        return default
开发者ID:dingboopt,项目名称:tricircle,代码行数:30,代码来源:utils.py


示例10: serve

def serve(xservice, workers=1):
    global _launcher
    if _launcher:
        raise RuntimeError(_('serve() can only be called once'))

    _launcher = srv.ProcessLauncher(CONF, restart_method='mutate')
    _launcher.launch_service(xservice, workers=workers)
开发者ID:daespinel,项目名称:tricircle,代码行数:7,代码来源:xservice.py


示例11: 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 context.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)
    elif read_deleted == 'int_no':
        query = query.filter_by(deleted=0)
    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:LongXQ,项目名称:tricircle,代码行数:31,代码来源:api.py


示例12: load_paste_app

def load_paste_app(app_name):
    """Builds and returns a WSGI app from a paste config file.

    :param app_name: Name of the application to load
    :raises ConfigFilesNotFoundError when config file cannot be located
    :raises RuntimeError when application cannot be loaded from config file
    """

    config_path = cfg.CONF.find_file(cfg.CONF.api_paste_config)
    if not config_path:
        raise cfg.ConfigFilesNotFoundError(
            config_files=[cfg.CONF.api_paste_config])
    config_path = os.path.abspath(config_path)
    LOG.info(_LI("Config paste file: %s"), config_path)

    try:
        app = deploy.loadapp("config:%s" % config_path, name=app_name)
    except (LookupError, ImportError):
        msg = (_("Unable to load %(app_name)s from "
                 "configuration file %(config_path)s.") %
               {'app_name': app_name,
                'config_path': config_path})
        LOG.exception(msg)
        raise RuntimeError(msg)
    return app
开发者ID:hannibalhuang,项目名称:tricircle,代码行数:25,代码来源:config.py


示例13: start

    def start(self):
        ver_str = version.version_info
        LOG.info(_LI('Starting %(topic)s node (version %(version)s)'),
                 {'topic': self.topic, 'version': ver_str})

        self.basic_config_check()
        self.manager.init_host()
        self.manager.pre_start_hook()

        LOG.debug(_("Creating RPC server for service %s"), self.topic)

        target = messaging.Target(topic=self.topic, server=self.host)

        endpoints = [
            self.manager,
            baserpc.BaseServerRPCAPI(self.manager.service_name)
        ]
        endpoints.extend(self.manager.additional_endpoints)

        self.rpc_server = rpc.get_server(target, endpoints, self.serializer)

        self.rpc_server.start()

        self.manager.post_start_hook()

        if self.periodic_enable:
            if self.periodic_fuzzy_delay:
                initial_delay = random.randint(0, self.periodic_fuzzy_delay)
            else:
                initial_delay = None

            self.tg.add_dynamic_timer(self.periodic_tasks,
                                      initial_delay=initial_delay,
                                      periodic_interval_max=self.interval_max)
开发者ID:Ronghui,项目名称:tricircle,代码行数:34,代码来源:xservice.py


示例14: _allocate_network_async

    def _allocate_network_async(self, context, instance, requested_networks,
                                macs, security_groups, is_vpn, dhcp_options):
        """Method used to allocate networks in the background.

        Broken out for testing.
        """
        LOG.debug("Allocating IP information in the background.",
                  instance=instance)
        retries = CONF.network_allocate_retries
        if retries < 0:
            LOG.warn(_("Treating negative config value (%(retries)s) for "
                       "'network_allocate_retries' as 0."),
                     {'retries': retries})
        attempts = retries > 1 and retries + 1 or 1
        retry_time = 1
        for attempt in range(1, attempts + 1):
            try:
                nwinfo = self.network_api.allocate_for_instance(
                    context, instance, vpn=is_vpn,
                    requested_networks=requested_networks,
                    macs=macs, security_groups=security_groups,
                    dhcp_options=dhcp_options)
                LOG.debug('Instance network_info: |%s|', nwinfo,
                          instance=instance)
                instance.system_metadata['network_allocated'] = 'True'
                # NOTE(JoshNang) do not save the instance here, as it can cause
                # races. The caller shares a reference to instance and waits
                # for this async greenthread to finish before calling
                # instance.save().
                return nwinfo
            except Exception:
                exc_info = sys.exc_info()
                log_info = {'attempt': attempt,
                            'attempts': attempts}
                if attempt == attempts:
                    LOG.exception(_LE('Instance failed network setup '
                                      'after %(attempts)d attempt(s)'),
                                  log_info)
                    raise exc_info[0], exc_info[1], exc_info[2]
                LOG.warn(_('Instance failed network setup '
                           '(attempt %(attempt)d of %(attempts)d)'),
                         log_info, instance=instance)
                time.sleep(retry_time)
                retry_time *= 2
                if retry_time > 30:
                    retry_time = 30
开发者ID:hannibalhuang,项目名称:tricircle,代码行数:46,代码来源:compute_manager.py


示例15: __init__

    def __init__(self, message=None, **kwargs):

        self.kwargs = kwargs
        self.kwargs['message'] = message

        if 'code' not in self.kwargs:
            self.kwargs['code'] = self.code

        for k, v in self.kwargs.items():
            if isinstance(v, Exception):
                self.kwargs[k] = six.text_type(v)

        if self._should_format():
            try:
                message = self.message % kwargs
            except Exception:

                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                exc_info = _('Exception class %s in string '
                             'format operation') % type(self).__name__
                format_str = _('%(exception_info)s ; %(format_key)s : '
                               '%(format_value)s')
                for name, value in kwargs.items():
                    exc_info = format_str % {
                        'exception_info': exc_info,
                        'format_key': name,
                        'format_value': six.text_type(value)}

                exc_info = _('%(message)s ; %(exception_info)s') % {
                    'message': self.message, 'exception_info': exc_info}
                LOG.exception(exc_info)

                # no rerasie
                # exc_info = sys.exc_info()
                # if CONF.fatal_exception_format_errors:
                #    six.reraise(*exc_info)

                # at least get the core message out if something happened
                message = self.message

        elif isinstance(message, Exception):
            message = six.text_type(message)

        self.msg = message
        super(TricircleException, self).__init__(message)
开发者ID:LongXQ,项目名称:tricircle,代码行数:46,代码来源:exceptions.py


示例16: put

    def put(self, **kw):

        context = t_context.extract_context_from_environ()
        if not context.is_admin:
            # TODO(joahuang): changed to policy control later
            # to support reseller admin mode
            return Response(_('Admin role required to update quota'), 409)

        return self._quota_action('put', **kw)
开发者ID:Ronghui,项目名称:tricircle,代码行数:9,代码来源:quota_sets.py


示例17: wrapper

 def wrapper(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except db_exc.DBDataError:
         msg = _('Error writing field to database')
         LOG.exception(msg)
         raise exceptions.Invalid(msg)
     except Exception as e:
         LOG.exception(str(e))
         raise
开发者ID:LongXQ,项目名称:tricircle,代码行数:10,代码来源:api.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap