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

Python gettextutils._函数代码示例

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

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



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

示例1: 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(_("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:MounikaPandiri,项目名称:mybackup,代码行数:25,代码来源:config.py


示例2: _verify_dict_keys

def _verify_dict_keys(expected_keys, target_dict, strict=True):
    """Allows to verify keys in a dictionary.

    :param expected_keys: A list of keys expected to be present.
    :param target_dict: The dictionary which should be verified.
    :param strict: Specifies whether additional keys are allowed to be present.
    :return: True, if keys in the dictionary correspond to the specification.
    """
    if not isinstance(target_dict, dict):
        msg = (_("Invalid input. '%(target_dict)s' must be a dictionary "
                 "with keys: %(expected_keys)s") %
               {'target_dict': target_dict, 'expected_keys': expected_keys})
        return msg

    expected_keys = set(expected_keys)
    provided_keys = set(target_dict.keys())

    predicate = expected_keys.__eq__ if strict else expected_keys.issubset

    if not predicate(provided_keys):
        msg = (_("Validation of dictionary's keys failed."
                 "Expected keys: %(expected_keys)s "
                 "Provided keys: %(provided_keys)s") %
               {'expected_keys': expected_keys,
                'provided_keys': provided_keys})
        return msg
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:26,代码来源:attributes.py


示例3: _parse_check

def _parse_check(rule):
    """
    Parse a single base check rule into an appropriate Check object.
    """

    # Handle the special checks
    if rule == '!':
        return FalseCheck()
    elif rule == '@':
        return TrueCheck()

    try:
        kind, match = rule.split(':', 1)
    except Exception:
        LOG.exception(_("Failed to understand rule %(rule)s") % locals())
        # If the rule is invalid, we'll fail closed
        return FalseCheck()

    # Find what implements the check
    if kind in _checks:
        return _checks[kind](kind, match)
    elif None in _checks:
        return _checks[None](kind, match)
    else:
        LOG.error(_("No handler for matches of kind %s") % kind)
        return FalseCheck()
开发者ID:hemanthnakkina,项目名称:vnfmanager,代码行数:26,代码来源:policy.py


示例4: _validate_range

def _validate_range(data, valid_values=None):
    """Check that integer value is within a range provided.

    Test is inclusive. Allows either limit to be ignored, to allow
    checking ranges where only the lower or upper limit matter.
    It is expected that the limits provided are valid integers or
    the value None.
    """

    min_value = valid_values[0]
    max_value = valid_values[1]
    try:
        data = int(data)
    except (ValueError, TypeError):
        msg = _("'%s' is not an integer") % data
        LOG.debug(msg)
        return msg
    if min_value is not UNLIMITED and data < min_value:
        msg = _("'%(data)s' is too small - must be at least "
                "'%(limit)d'") % {'data': data, 'limit': min_value}
        LOG.debug(msg)
        return msg
    if max_value is not UNLIMITED and data > max_value:
        msg = _("'%(data)s' is too large - must be no larger than "
                "'%(limit)d'") % {'data': data, 'limit': max_value}
        LOG.debug(msg)
        return msg
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:27,代码来源:attributes.py


示例5: inner

 def inner(*args, **kwargs):
     try:
         with lock(name, lock_file_prefix, external, lock_path):
             LOG.debug(_('Got semaphore / lock "%(function)s"'),
                       {'function': f.__name__})
             return f(*args, **kwargs)
     finally:
         LOG.debug(_('Semaphore / lock released "%(function)s"'),
                   {'function': f.__name__})
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:9,代码来源:lockutils.py


示例6: send_ack

 def send_ack(self, context, vnfd, vdu, instance, status, nsd_id):
     if status == 'COMPLETE':
         self.plugin.build_acknowledge_list(context, vnfd, vdu, instance,
                                            status, nsd_id)
         LOG.debug(_('ACK received from VNFManager: '
                     'Configuration complete for VNF %s'), instance)
     else:
         self.plugin.build_acknowledge_list(context,vnfd, vdu, instance,
                                            status, nsd_id)
         LOG.debug(_('ACK received from VNFManager: '
                     'Confguration failed for VNF %s'), instance)
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:11,代码来源:plugin.py


示例7: validate_head_file

def validate_head_file(config):
    script = alembic_script.ScriptDirectory.from_config(config)
    if len(script.get_heads()) > 1:
        alembic_util.err(_('Timeline branches unable to generate timeline'))

    head_path = os.path.join(script.versions, HEAD_FILENAME)
    if (os.path.isfile(head_path) and
        open(head_path).read().strip() == script.get_current_head()):
        return
    else:
        alembic_util.err(_('HEAD file does not match migration timeline head'))
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:11,代码来源:cli.py


示例8: _validate_string

def _validate_string(data, max_len=None):
    if not isinstance(data, basestring):
        msg = _("'%s' is not a valid string") % data
        LOG.debug(msg)
        return msg

    if max_len is not None and len(data) > max_len:
        msg = (_("'%(data)s' exceeds maximum length of %(max_len)s") %
               {'data': data, 'max_len': max_len})
        LOG.debug(msg)
        return msg
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:11,代码来源:attributes.py


示例9: _validate_non_negative

def _validate_non_negative(data, valid_values=None):
    try:
        data = int(data)
    except (ValueError, TypeError):
        msg = _("'%s' is not an integer") % data
        LOG.debug(msg)
        return msg

    if data < 0:
        msg = _("'%s' should be non-negative") % data
        LOG.debug(msg)
        return msg
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:12,代码来源:attributes.py


示例10: _run_wsgi

def _run_wsgi(app_name):
    app = config.load_paste_app(app_name)
    if not app:
        LOG.error(_('No known API applications configured.'))
        return
    server = wsgi.Server("vnfsvc")
    server.start(app, cfg.CONF.bind_port, cfg.CONF.bind_host)
    # Dump all option values here after all options are parsed
    cfg.CONF.log_opt_values(LOG, std_logging.DEBUG)
    LOG.info(_("VNF service started, listening on %(host)s:%(port)s"),
             {'host': cfg.CONF.bind_host,
              'port': cfg.CONF.bind_port})
    return server
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:13,代码来源:service.py


示例11: _get_plugin_instance

 def _get_plugin_instance(self, namespace, plugin_provider):
     try:
         # Try to resolve plugin by name
         mgr = driver.DriverManager(namespace, plugin_provider)
         plugin_class = mgr.driver
     except RuntimeError as e1:
         # fallback to class name
         try:
             plugin_class = importutils.import_class(plugin_provider)
         except ImportError as e2:
             LOG.exception(_("Error loading plugin by name, %s"), e1)
             LOG.exception(_("Error loading plugin by class, %s"), e2)
             raise ImportError(_("Plugin not found."))
     return plugin_class()
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:14,代码来源:manager.py


示例12: read

 def read(self, i=None):
     result = self.data.read(i)
     self.bytes_read += len(result)
     if self.bytes_read > self.limit:
         msg = _("Request is too large.")
         raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg)
     return result
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:7,代码来源:sizelimit.py


示例13: _populate_tenant_id

    def _populate_tenant_id(context, res_dict, is_create):

        if (('tenant_id' in res_dict and
             res_dict['tenant_id'] != context.tenant_id and
             not context.is_admin)):
            msg = _("Specifying 'tenant_id' other than authenticated "
                    "tenant in request requires admin privileges")
            raise webob.exc.HTTPBadRequest(msg)

        if is_create and 'tenant_id' not in res_dict:
            if context.tenant_id:
                res_dict['tenant_id'] = context.tenant_id
            else:
                msg = _("Running without keystone AuthN requires "
                        " that tenant_id is specified")
                raise webob.exc.HTTPBadRequest(msg)
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:16,代码来源:base.py


示例14: _validate_uuid_list

def _validate_uuid_list(data, valid_values=None):
    if not isinstance(data, list):
        msg = _("'%s' is not a list") % data
        LOG.debug(msg)
        return msg

    for item in data:
        msg = _validate_uuid(item)
        if msg:
            LOG.debug(msg)
            return msg

    if len(set(data)) != len(data):
        msg = _("Duplicate items in the list: '%s'") % ', '.join(data)
        LOG.debug(msg)
        return msg
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:16,代码来源:attributes.py


示例15: _to_xml_node

 def _to_xml_node(self, parent, metadata, nodename, data, used_prefixes):
     """Recursive method to convert data members to XML nodes."""
     result = etree.SubElement(parent, nodename)
     if ":" in nodename:
         used_prefixes.append(nodename.split(":", 1)[0])
     if isinstance(data, list):
         if not data:
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_LIST)
             return result
         singular = metadata.get('plurals', {}).get(nodename, None)
         if singular is None:
             if nodename.endswith('s'):
                 singular = nodename[:-1]
             else:
                 singular = 'item'
         for item in data:
             self._to_xml_node(result, metadata, singular, item,
                               used_prefixes)
     elif isinstance(data, dict):
         if not data:
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_DICT)
             return result
         attrs = metadata.get('attributes', {}).get(nodename, {})
         for k, v in data.items():
             if k in attrs:
                 result.set(k, str(v))
             else:
                 self._to_xml_node(result, metadata, k, v,
                                   used_prefixes)
     elif data is None:
         result.set(constants.XSI_ATTR, 'true')
     else:
         if isinstance(data, bool):
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_BOOL)
         elif isinstance(data, int):
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_INT)
         elif isinstance(data, long):
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_LONG)
         elif isinstance(data, float):
             result.set(
                 constants.TYPE_ATTR,
                 constants.TYPE_FLOAT)
         LOG.debug(_("Data %(data)s type is %(type)s"),
                   {'data': data,
                    'type': type(data)})
         if isinstance(data, str):
             result.text = unicode(data, 'utf-8')
         else:
             result.text = unicode(data)
     return result
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:60,代码来源:wsgi.py


示例16: __call__

    def __call__(self, req):
        """Call the method specified in req.environ by RoutesMiddleware."""
        arg_dict = req.environ['wsgiorg.routing_args'][1]
        action = arg_dict['action']
        method = getattr(self, action)
        del arg_dict['controller']
        del arg_dict['action']
        if 'format' in arg_dict:
            del arg_dict['format']
        arg_dict['request'] = req
        result = method(**arg_dict)

        if isinstance(result, dict) or result is None:
            if result is None:
                status = 204
                content_type = ''
                body = None
            else:
                status = 200
                content_type = req.best_match_content_type()
                default_xmlns = self.get_default_xmlns(req)
                body = self._serialize(result, content_type, default_xmlns)

            response = webob.Response(status=status,
                                      content_type=content_type,
                                      body=body)
            msg_dict = dict(url=req.url, status=response.status_int)
            msg = _("%(url)s returned with HTTP %(status)d") % msg_dict
            LOG.debug(msg)
            return response
        else:
            return result
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:32,代码来源:wsgi.py


示例17: execute

def execute(cmd, root_helper=None, process_input=None, addl_env=None,
            check_exit_code=True, return_stderr=False):
    try:
        obj, cmd = create_process(cmd, root_helper=root_helper,
                                  addl_env=addl_env)
        _stdout, _stderr = (process_input and
                            obj.communicate(process_input) or
                            obj.communicate())
        obj.stdin.close()
        m = _("\nCommand: %(cmd)s\nExit code: %(code)s\nStdout: %(stdout)r\n"
              "Stderr: %(stderr)r") % {'cmd': cmd, 'code': obj.returncode,
                                       'stdout': _stdout, 'stderr': _stderr}
        if obj.returncode:
            LOG.error(m)
            if check_exit_code:
                raise RuntimeError(m)
        else:
            LOG.debug(m)
    finally:
        # NOTE(termie): this appears to be necessary to let the subprocess
        #               call clean something up in between calls, without
        #               it two execute calls in a row hangs the second one
        greenthread.sleep(0)

    return return_stderr and (_stdout, _stderr) or _stdout
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:25,代码来源:utils.py


示例18: __exit__

 def __exit__(self, exc_type, exc_val, exc_tb):
     try:
         self.unlock()
         self.lockfile.close()
     except IOError:
         LOG.exception(_("Could not release the acquired lock `%s`"),
                       self.fname)
开发者ID:MounikaPandiri,项目名称:mybackup,代码行数:7,代码来源:lockutils.py


示例19: initialize_if_enabled

def initialize_if_enabled():
    backdoor_locals = {
        'exit': _dont_use_this,      # So we don't exit the entire process
        'quit': _dont_use_this,      # So we don't exit the entire process
        'fo': _find_objects,
        'pgt': _print_greenthreads,
        'pnt': _print_nativethreads,
    }

    if CONF.backdoor_port is None:
        return None

    start_port, end_port = _parse_port_range(str(CONF.backdoor_port))

    # NOTE(johannes): The standard sys.displayhook will print the value of
    # the last expression and set it to __builtin__._, which overwrites
    # the __builtin__._ that gettext sets. Let's switch to using pprint
    # since it won't interact poorly with gettext, and it's easier to
    # read the output too.
    def displayhook(val):
        if val is not None:
            pprint.pprint(val)
    sys.displayhook = displayhook

    sock = _listen('localhost', start_port, end_port, eventlet.listen)

    # In the case of backdoor port being zero, a port number is assigned by
    # listen().  In any case, pull the port number out here.
    port = sock.getsockname()[1]
    LOG.info(_('Eventlet backdoor listening on %(port)s for process %(pid)d') %
             {'port': port, 'pid': os.getpid()})
    eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock,
                     locals=backdoor_locals)
    return port
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:34,代码来源:eventlet_backdoor.py


示例20: _from_xml

 def _from_xml(self, datastring):
     if datastring is None:
         return None
     plurals = set(self.metadata.get('plurals', {}))
     try:
         node = self._parseXML(datastring)
         root_tag = self._get_key(node.tag)
         # Deserialize link node was needed by unit test for verifying
         # the request's response
         links = self._get_links(root_tag, node)
         result = self._from_xml_node(node, plurals)
         # root_tag = constants.VIRTUAL_ROOT_KEY and links is not None
         # is not possible because of the way data are serialized.
         if root_tag == constants.VIRTUAL_ROOT_KEY:
             return result
         return dict({root_tag: result}, **links)
     except Exception as e:
         with excutils.save_and_reraise_exception():
             parseError = False
             # Python2.7
             if (hasattr(etree, 'ParseError') and
                 isinstance(e, getattr(etree, 'ParseError'))):
                 parseError = True
             # Python2.6
             elif isinstance(e, expat.ExpatError):
                 parseError = True
             if parseError:
                 msg = _("Cannot understand XML")
                 raise exception.MalformedRequestBody(reason=msg)
开发者ID:hemanthnakkina,项目名称:vnfsvc,代码行数:29,代码来源:wsgi.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python event.Event类代码示例发布时间:2022-05-26
下一篇:
Python gettextutils._函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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