Python string 模块,Formatter() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.Formatter()

项目:django-tree    作者:BertrandBordage    | 项目源码 | 文件源码
def format_sql_in_function(sql, into=None):
    kwargs = AnyArg({'USING': AnyUsingArg()})
    # TODO: Replace Formatter with sql.format(**kwargs) when dropping Python 2.
    sql = Formatter().vformat(sql, (), kwargs).replace("'", "''")
    using = kwargs.pop('USING')
    args = ', '.join([k for k in kwargs])

    extra = ''
    if into is not None:
        extra += ' INTO ' + ', '.join(into)
    if using:
        extra += ' USING ' + ', '.join([a for a in using])

    return "EXECUTE format('%s', %s)%s;" % (sql, args, extra)


# TODO: Add `LIMIT 1` where appropriate to see if it optimises a bit.
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:rapier    作者:apigee-labs    | 项目源码 | 文件源码
def __init__(self, permalink_template, entity_uri, generator):
        self.permalink_template = permalink_template if hasattr(permalink_template, 'keys') else {'template': permalink_template}
        self.entity_uri = entity_uri
        self.generator = generator
        template = self.permalink_template['template']
        formatter = string.Formatter()
        try:
            parsed_format = list(formatter.parse(template))
        except Exception as e:
            sys.exit('error parsing permalinkTemplate template: %s e:' % (template, e))
        leading_parts = [part for part in parsed_format if part[1] is not None]
        if len(leading_parts) != 1:
            sys.exit('permalinkTemplate template %s must include exactly one {name} element after ;' % query_path_segment_string)
        else:
            part = leading_parts[0]
        if part[1] == '':
            self.error('property name required between {} characters after %s in permalinkTemplate template %s' %(leading_parts[0] ,query_path_segment_string))
        else:
            self.implementation_url_variable_name = part[1]
项目:rapier    作者:apigee-labs    | 项目源码 | 文件源码
def validate_query_path_segment_string(self, node, key, query_path_segment_string):
        parts = query_path_segment_string.split(';')
        if len(parts) == 1: # no ';'
            pass
        elif len(parts) == 2: # found ';'
            params_part = parts[1]
            formatter = string.Formatter()
            try:
                parsed_format = list(formatter.parse(params_part))
            except Exception as e:
                return self.error('error parsing query path segment string: %s' % e, key)
            leading_parts = [part for part in parsed_format if part[1] is not None]
            if len(leading_parts) == 0:
                self.error('query segment %s must include at least one {name} element after ;' % query_path_segment_string)
            if len ([part for part in leading_parts if part[1] == '']) > 0:
                self.error('property name required between {} characters after %s in query segment %s' %([part[0] for part in leading_parts if part[1]] ,query_path_segment_string))
项目:RPoint    作者:george17-meet    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:behem0th    作者:robot0nfire    | 项目源码 | 文件源码
def _print(str, *args, **kwargs):
    if NO_LOG:
        return

    str = Formatter().vformat(str, args, kwargs)
    str = str.replace('\n', '\n' + ' ' * 11)

    stack = inspect.stack()

    # Stack depth has to be atleast 3 normally, since _print() should
    # be normally only be called from info{_v}(), warn() or error().
    # But we still take care of edge cases where this may not be true.
    frame = stack[2][0] if len(stack) >= 3 else None
    class_ = frame.f_locals['self'].__class__.__name__ if frame and 'self' in frame.f_locals else '<unknown>'
    thread = threading.current_thread().name

    print(BEHEM0TH_COLOR + '[behem0th]',
        CLASS_COLOR + '[' + class_ + ']',
        THREAD_COLOR + thread + ':', str, CLEAR_FORMAT)
项目:Indushell    作者:SecarmaLabs    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:flask_system    作者:prashasy    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:FileStoreGAE    作者:liantian-cn    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:python-group-proj    作者:Sharcee    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:islam-buddy    作者:hamir    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_override_get_value(self):
        class NamespaceFormatter(string.Formatter):
            def __init__(self, namespace={}):
                string.Formatter.__init__(self)
                self.namespace = namespace

            def get_value(self, key, args, kwds):
                if isinstance(key, str):
                    try:
                        # Check explicitly passed arguments first
                        return kwds[key]
                    except KeyError:
                        return self.namespace[key]
                else:
                    string.Formatter.get_value(key, args, kwds)

        fmt = NamespaceFormatter({'greeting':'hello'})
        self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
项目:splunk_ta_ps4_f1_2016    作者:jonathanvarley    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:django-rdf-io    作者:rob-metalinkage    | 项目源码 | 文件源码
def resolveTemplate(template, model, obj) :
    from rdf_io.models import getattr_path, ConfigVar
    vals = { 'model' : model }
    for (literal,param,repval,conv) in Formatter().parse(template) :
        if param and param != 'model' :
            if( param[0] == '_' ) :
                val = ConfigVar.getval(param[1:])
                if val:
                    vals[param] = val
                else:
                    raise Exception( "template references unset ConfigVariable %s" % param[1:])
            else:
                try:
                    vals[param] = iter(getattr_path(obj,param)).next()
                except:
                    if param == 'slug'  :
                        vals[param] = obj.id

    try:
        return template.format(**vals)
    except KeyError as e :
        raise KeyError( 'Property %s of model %s not found when creating API URL' % (e,model))
项目:jieba-GAE    作者:liantian-cn    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:koi    作者:openpermissions    | 项目源码 | 文件源码
def add_path_part(url, regex=PATH_PART):
    """
    replace the variables in a url template with regex named groups
    :param url: string of a url template
    :param regex: regex of the named group
    :returns: regex
    """
    formatter = string.Formatter()
    url_var_template = "(?P<{var_name}>{regex})"

    for part in formatter.parse(url):
        string_part, var_name, _, _ = part
        if string_part:
            yield string_part
        if var_name:
            yield url_var_template.format(var_name=var_name, regex=regex)
项目:pipenv    作者:pypa    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_auto_numbering(self):
        fmt = string.Formatter()
        self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
                         'foo{}{}'.format('bar', 6))
        self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
                         'foo{1}{num}{1}'.format(None, 'bar', num=6))
        self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
                         '{:^{}}'.format('bar', 6))
        self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
                         '{:^{}} {}'.format('bar', 6, 'X'))
        self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
                         '{:^{pad}}{}'.format('foo', 'bar', pad=6))

        with self.assertRaises(ValueError):
            fmt.format('foo{1}{}', 'bar', 6)

        with self.assertRaises(ValueError):
            fmt.format('foo{}{1}', 'bar', 6)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_override_get_value(self):
        class NamespaceFormatter(string.Formatter):
            def __init__(self, namespace={}):
                string.Formatter.__init__(self)
                self.namespace = namespace

            def get_value(self, key, args, kwds):
                if isinstance(key, str):
                    try:
                        # Check explicitly passed arguments first
                        return kwds[key]
                    except KeyError:
                        return self.namespace[key]
                else:
                    string.Formatter.get_value(key, args, kwds)

        fmt = NamespaceFormatter({'greeting':'hello'})
        self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def collect_string_fields(format_string):
    """ Given a format string, return an iterator
    of all the valid format fields. It handles nested fields
    as well.
    """

    formatter = string.Formatter()
    try:
        parseiterator = formatter.parse(format_string)
        for result in parseiterator:
            if all(item is None for item in result[1:]):
                # not a replacement format
                continue
            name = result[1]
            nested = result[2]
            yield name
            if nested:
                for field in collect_string_fields(nested):
                    yield field
    except ValueError:
        # probably the format string is invalid
        # should we check the argument of the ValueError?
        raise utils.IncompleteFormatString(format_string)
项目:QualquerMerdaAPI    作者:tiagovizoto    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:gardenbot    作者:GoestaO    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def collect_string_fields(format_string):
    """ Given a format string, return an iterator
    of all the valid format fields. It handles nested fields
    as well.
    """

    formatter = string.Formatter()
    try:
        parseiterator = formatter.parse(format_string)
        for result in parseiterator:
            if all(item is None for item in result[1:]):
                # not a replacement format
                continue
            name = result[1]
            nested = result[2]
            yield name
            if nested:
                for field in collect_string_fields(nested):
                    yield field
    except ValueError:
        # probably the format string is invalid
        # should we check the argument of the ValueError?
        raise utils.IncompleteFormatString(format_string)
项目:ieee-cs-txst    作者:codestar12    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_auto_numbering(self):
        fmt = string.Formatter()
        self.assertEqual(fmt.format('foo{}{}', 'bar', 6),
                         'foo{}{}'.format('bar', 6))
        self.assertEqual(fmt.format('foo{1}{num}{1}', None, 'bar', num=6),
                         'foo{1}{num}{1}'.format(None, 'bar', num=6))
        self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
                         '{:^{}}'.format('bar', 6))
        self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
                         '{:^{pad}}{}'.format('foo', 'bar', pad=6))

        with self.assertRaises(ValueError):
            fmt.format('foo{1}{}', 'bar', 6)

        with self.assertRaises(ValueError):
            fmt.format('foo{}{1}', 'bar', 6)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_check_unused_args(self):
        class CheckAllUsedFormatter(string.Formatter):
            def check_unused_args(self, used_args, args, kwargs):
                # Track which arguments actually got used
                unused_args = set(kwargs.keys())
                unused_args.update(range(0, len(args)))

                for arg in used_args:
                    unused_args.remove(arg)

                if unused_args:
                    raise ValueError("unused arguments")

        fmt = CheckAllUsedFormatter()
        self.assertEqual(fmt.format("{0}", 10), "10")
        self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
        self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
        self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
        self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
        self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
项目:WhatTheHack    作者:Sylphias    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:WhatTheHack    作者:Sylphias    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
def collect_string_fields(format_string):
    """ Given a format string, return an iterator
    of all the valid format fields. It handles nested fields
    as well.
    """

    formatter = string.Formatter()
    try:
        parseiterator = formatter.parse(format_string)
        for result in parseiterator:
            if all(item is None for item in result[1:]):
                # not a replacement format
                continue
            name = result[1]
            nested = result[2]
            yield name
            if nested:
                for field in collect_string_fields(nested):
                    yield field
    except ValueError:
        # probably the format string is invalid
        # should we check the argument of the ValueError?
        raise utils.IncompleteFormatString(format_string)
项目:flask    作者:bobohope    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                # We need to make sure the format spec is unicode here as
                # otherwise the wrong callback methods are invoked.  For
                # instance a byte string there would invoke __str__ and
                # not __unicode__.
                rv = string.Formatter.format_field(
                    self, value, text_type(format_spec))
            return text_type(self.escape(rv))
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def collect_string_fields(format_string):
    """ Given a format string, return an iterator
    of all the valid format fields. It handles nested fields
    as well.
    """

    formatter = string.Formatter()
    try:
        parseiterator = formatter.parse(format_string)
        for result in parseiterator:
            if all(item is None for item in result[1:]):
                # not a replacement format
                continue
            name = result[1]
            nested = result[2]
            yield name
            if nested:
                for field in collect_string_fields(nested):
                    yield field
    except ValueError:
        # probably the format string is invalid
        # should we check the argument of the ValueError?
        raise utils.IncompleteFormatString(format_string)
项目:gazelle-cli    作者:spiritualized    | 项目源码 | 文件源码
def _process_format( self, format_string ):
        out = []
        args = dict( self.__dict__ )
        args["peer_info"] = ( "{peers_connected}/{peers_total}" if args["progress"] == 100 else "{seeds_connected}/{seeds_total}" ).format( **args )
        args["label"] = "({label})".format( **args ) if args["label"] != "" else ""
        if args["dl_speed"] < 1024:
            args["dl_speed_h"] = ""
        if args["ul_speed"] < 1024:
            args["ul_speed_h"] = ""
        if args["dl_remain"] == 0:
            args["dl_remain_h"] = ""
        formatter = string.Formatter( )
        for literal_text, field_name, format_spec, conversion in formatter.parse( format_string ):
            elem = { "before": literal_text, "value": "" }
            if field_name is not None:
                def_field_name, def_format_spec, def_conversion = None, " <20", None
                if field_name in self._default_format_specs:
                    def_field_name, def_format_spec, def_conversion = next( formatter.parse( self._default_format_specs[field_name] ) )[1:4]
                val = formatter.get_field( field_name if def_field_name is None else def_field_name, None, args )[0]
                val = formatter.convert_field( val, conversion if conversion is not None else def_conversion )
                val = formatter.format_field( val, format_spec if format_spec != "" else def_format_spec )
                elem["value"] = val
            out.append( elem )
        return out
项目:agdc_statistics    作者:GeoscienceAustralia    | 项目源码 | 文件源码
def valid_format_string(valid_fields):
    """
    Ensure that the provided string can be parsed as a python format string, and contains only `valid_fields`
    :param valid_fields: set or sequence of valid field names
    """
    f = Formatter()
    valid_fields = set(valid_fields)

    def validate_string(format_string):
        fields = set(field_name for _, field_name, _, _ in f.parse(format_string) if field_name)

        if fields < valid_fields:
            return format_string
        else:
            raise Invalid('format string specifies invalid field(s): %s' % (fields - valid_fields))

    return validate_string
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))
项目:ovirtcmd    作者:fbacchella    | 项目源码 | 文件源码
def to_str(self, item):
        formatter = string.Formatter()
        values = {}
        for i in formatter.parse(self.template):
            values[i[1]] = getattr(item, i[1])
        return  "%s" %(formatter.format(self.template, **values))
项目:user-sync.py    作者:adobe-apiplatform    | 项目源码 | 文件源码
def __init__(self, string_format):
        """
        The format string must be a unicode or ascii string: see notes above about being careful in Py2!
        """
        if string_format is None:
            attribute_names = []
        else:
            string_format = six.text_type(string_format)    # force unicode so attribute values are unicode
            formatter = string.Formatter()
            attribute_names = [six.text_type(item[1]) for item in formatter.parse(string_format) if item[1]]
        self.string_format = string_format
        self.attribute_names = attribute_names
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))
项目:salt-vault    作者:carlpett    | 项目源码 | 文件源码
def _expand_pattern_lists(pattern, **mappings):
  '''
  Expands the pattern for any list-valued mappings, such that for any list of
  length N in the mappings present in the pattern, N copies of the pattern are
  returned, each with an element of the list substituted.

  pattern:
      A pattern to expand, for example 'by-role/{grains[roles]}'

  mappings:
      A dictionary of variables that can be expanded into the pattern.

  Example: Given the pattern 'by-role/{grains[roles]}' and the below grains

  .. code-block:: yaml

      grains:
          roles:
              - web
              - database

  This function will expand that into '[by-role/web, by-role/database]'.

  Note that this method does not expand any non-list patterns.
  '''
  expanded_patterns = []
  f = string.Formatter()
  for (_, field_name, _, _) in f.parse(pattern):
    if field_name is None:
      continue
    (value, _) = f.get_field(field_name, None, mappings)
    if isinstance(value, list):
      token = '{{{0}}}'.format(field_name)
      expanded = map(lambda x: pattern.replace(token, str(x)), value)
      for expanded_item in expanded:
        result = _expand_pattern_lists(expanded_item, **mappings)
        expanded_patterns += result
      return expanded_patterns
  return [pattern]
项目:rapier    作者:apigee-labs    | 项目源码 | 文件源码
def build_params(self):
        formatter = string.Formatter()
        param_names = [part[1] for part in formatter.parse(self.base_URL) if part[1] is not None]
        return [{
                'name': param_name,
                'in': 'path',
                'type': 'string',
                'required': True
                } for param_name in param_names]
项目:rapier    作者:apigee-labs    | 项目源码 | 文件源码
def validate_permalink_template_template(self, node, key, template):
        formatter = string.Formatter()
        try:
            parsed_format = list(formatter.parse(template))
        except Exception as e:
            return self.error('error parsing query path segment string: %s' % e, key)
        leading_parts = [part for part in parsed_format if part[1] is not None]
        if len(leading_parts) != 1:
            self.error('permalinkTemplate template %s must include exactly one {name} element after ;' % query_path_segment_string)
        else:
            part = leading_parts[0]
        if part[1] == '':
            self.error('property name required between {} characters after %s in permalinkTemplate template %s' %(leading_parts[0] ,query_path_segment_string))
项目:baka    作者:baka-framework    | 项目源码 | 文件源码
def __init__(self, setting, link, pattern):
        self.setting = setting
        self.link = link.upper()
        self.pattern = pattern

        # Determine the settings that need to be present
        formatter = string.Formatter()
        self.placeholders = [field
                             for _, field, _, _ in formatter.parse(pattern)
                             if field is not None]
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def format_field(self, value, format_spec):
            if hasattr(value, '__html_format__'):
                rv = value.__html_format__(format_spec)
            elif hasattr(value, '__html__'):
                if format_spec:
                    raise ValueError('No format specification allowed '
                                     'when formatting an object with '
                                     'its __html__ method.')
                rv = value.__html__()
            else:
                rv = string.Formatter.format_field(self, value, format_spec)
            return text_type(self.escape(rv))