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

Python _compat.iteritems函数代码示例

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

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



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

示例1: test_basic

    def test_basic(self):
        @datastructures.native_itermethods(['keys', 'values', 'items'])
        class StupidDict(object):
            def keys(self, multi=1):
                return iter(['a', 'b', 'c'] * multi)

            def values(self, multi=1):
                return iter([1, 2, 3] * multi)

            def items(self, multi=1):
                return iter(zip(iterkeys(self, multi=multi),
                                itervalues(self, multi=multi)))

        d = StupidDict()
        expected_keys = ['a', 'b', 'c']
        expected_values = [1, 2, 3]
        expected_items = list(zip(expected_keys, expected_values))

        self.assert_equal(list(iterkeys(d)), expected_keys)
        self.assert_equal(list(itervalues(d)), expected_values)
        self.assert_equal(list(iteritems(d)), expected_items)

        self.assert_equal(list(iterkeys(d, 2)), expected_keys * 2)
        self.assert_equal(list(itervalues(d, 2)), expected_values * 2)
        self.assert_equal(list(iteritems(d, 2)), expected_items * 2)
开发者ID:fdion,项目名称:webfive-pyjs,代码行数:25,代码来源:datastructures.py


示例2: test_basic

    def test_basic(self):
        @datastructures.native_itermethods(["keys", "values", "items"])
        class StupidDict(object):
            def keys(self, multi=1):
                return iter(["a", "b", "c"] * multi)

            def values(self, multi=1):
                return iter([1, 2, 3] * multi)

            def items(self, multi=1):
                return iter(
                    zip(iterkeys(self, multi=multi), itervalues(self, multi=multi))
                )

        d = StupidDict()
        expected_keys = ["a", "b", "c"]
        expected_values = [1, 2, 3]
        expected_items = list(zip(expected_keys, expected_values))

        assert list(iterkeys(d)) == expected_keys
        assert list(itervalues(d)) == expected_values
        assert list(iteritems(d)) == expected_items

        assert list(iterkeys(d, 2)) == expected_keys * 2
        assert list(itervalues(d, 2)) == expected_values * 2
        assert list(iteritems(d, 2)) == expected_items * 2
开发者ID:pallets,项目名称:werkzeug,代码行数:26,代码来源:test_datastructures.py


示例3: change_table_sql

    def change_table_sql(self, db_type, old_fields, new_fields):

        def recreate(comp):
            for key, (old_field, new_field) in iteritems(comp):
                if old_field and new_field:
                    if old_field['field_name'] != new_field['field_name']:
                        return True
                    elif old_field['default_value'] != new_field['default_value']:
                        return True
                elif old_field and not new_field:
                    return True

        db_module = db_modules.get_db_module(db_type)
        table_name = self.f_table_name.value
        result = []
        comp = {}
        for field in old_fields:
            comp[field['id']] = [field, None]
        for field in new_fields:
            if comp.get(field['id']):
                comp[field['id']][1] = field
            else:
                if field['id']:
                    comp[field['id']] = [None, field]
                else:
                    comp[field['field_name']] = [None, field]
        if db_type == db_modules.SQLITE and recreate(comp):
            result += self.recreate_table_sql(db_type, old_fields, new_fields)
        else:
            for key, (old_field, new_field) in iteritems(comp):
                if old_field and not new_field and db_type != db_modules.SQLITE:
                    result.append(db_module.del_field_sql(table_name, old_field))
            for key, (old_field, new_field) in iteritems(comp):
                if old_field and new_field and db_type != db_modules.SQLITE:
                    if (old_field['field_name'] != new_field['field_name']) or \
                        (db_module.FIELD_TYPES[old_field['data_type']] != db_module.FIELD_TYPES[new_field['data_type']]) or \
                        (old_field['default_value'] != new_field['default_value']) or \
                        (old_field['size'] != new_field['size']):
                        sql = db_module.change_field_sql(table_name, old_field, new_field)
                        if type(sql) in (list, tuple):
                            result += sql
                        else:
                            result.append()
            for key, (old_field, new_field) in iteritems(comp):
                if not old_field and new_field:
                    result.append(db_module.add_field_sql(table_name, new_field))
        for i, s in enumerate(result):
            print(result[i])
        return result
开发者ID:jam-py,项目名称:jam-py,代码行数:49,代码来源:sql.py


示例4: print_usage

def print_usage(actions):
    """Print the usage information.  (Help screen)"""
    _deprecated()
    actions = sorted(iteritems(actions))
    print('usage: %s <action> [<options>]' % basename(sys.argv[0]))
    print('       %s --help' % basename(sys.argv[0]))
    print()
    print('actions:')
    for name, (func, doc, arguments) in actions:
        print('  %s:' % name)
        for line in doc.splitlines():
            print('    %s' % line)
        if arguments:
            print()
        for arg, shortcut, default, argtype in arguments:
            if isinstance(default, bool):
                print('    %s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg
                ))
            else:
                print('    %-30s%-10s%s' % (
                    (shortcut and '-%s, ' % shortcut or '') + '--' + arg,
                    argtype, default
                ))
        print()
开发者ID:2009bpy,项目名称:werkzeug,代码行数:25,代码来源:script.py


示例5: restart_with_reloader

def restart_with_reloader():
    """Spawn a new Python interpreter with the same arguments as this one,
    but running the reloader thread.
    """
    while 1:
        _log('info', ' * Restarting with reloader')

        requires_shell = False

        if sys.executable:
            args = [sys.executable] + sys.argv
        else:
            args, requires_shell = detect_executable()

        new_environ = os.environ.copy()
        new_environ['WERKZEUG_RUN_MAIN'] = 'true'

        # a weird bug on windows. sometimes unicode strings end up in the
        # environment and subprocess.call does not like this, encode them
        # to latin1 and continue.
        if os.name == 'nt' and PY2:
            for key, value in iteritems(new_environ):
                if isinstance(value, text_type):
                    new_environ[key] = value.encode('iso-8859-1')

        exit_code = subprocess.call(args, env=new_environ, shell=requires_shell)
        if exit_code != 3:
            return exit_code
开发者ID:transistor1,项目名称:werkzeug,代码行数:28,代码来源:serving.py


示例6: restart_with_reloader

    def restart_with_reloader(self):
        """Spawn a new Python interpreter with the same arguments as this one,
        but running the reloader thread.
        """
        while 1:
            _log('info', ' * Restarting with %s' % self.name)
            args = _get_args_for_reloading()

            # a weird bug on windows. sometimes unicode strings end up in the
            # environment and subprocess.call does not like this, encode them
            # to latin1 and continue.
            if os.name == 'nt' and PY2:
                new_environ = {}
                for key, value in iteritems(os.environ):
                    if isinstance(key, text_type):
                        key = key.encode('iso-8859-1')
                    if isinstance(value, text_type):
                        value = value.encode('iso-8859-1')
                    new_environ[key] = value
            else:
                new_environ = os.environ.copy()

            new_environ['WERKZEUG_RUN_MAIN'] = 'true'
            exit_code = subprocess.call(args, env=new_environ,
                                        close_fds=False)
            if exit_code != 3:
                return exit_code
开发者ID:gaoussoucamara,项目名称:simens-cerpad,代码行数:27,代码来源:_reloader.py


示例7: restart_with_reloader

def restart_with_reloader():
    """Spawn a new Python interpreter with the same arguments as this one,
    but running the reloader thread.
    """
    while 1:
        _log('info', ' * Restarting with reloader')
        #fix lastest python version entry_point script file incompatible bug
        if sys.argv[0].endswith('.pyw') or sys.argv[0].endswith('.py'):
            args = [sys.executable] + sys.argv
        else:
            args = sys.argv
        new_environ = os.environ.copy()
        new_environ['WERKZEUG_RUN_MAIN'] = 'true'

        # a weird bug on windows. sometimes unicode strings end up in the
        # environment and subprocess.call does not like this, encode them
        # to latin1 and continue.
        if os.name == 'nt' and PY2:
            for key, value in iteritems(new_environ):
                if isinstance(value, text_type):
                    new_environ[key] = value.encode('iso-8859-1')

        exit_code = subprocess.call(args, env=new_environ)
        if exit_code != 3:
            return exit_code
开发者ID:limodou,项目名称:uliweb,代码行数:25,代码来源:serving.py


示例8: group_clause

 def group_clause(self, query, fields, db_module=None):
     if db_module is None:
         db_module = self.task.db_module
     group_fields = query.get('__group_by')
     funcs = query.get('__funcs')
     if funcs:
         functions = {}
         for key, value in iteritems(funcs):
             functions[key.upper()] = value
     result = ''
     if group_fields:
         for field_name in group_fields:
             field = self._field_by_name(field_name)
             if query['__expanded'] and field.lookup_item and field.data_type != common.KEYS:
                 func = functions.get(field.field_name.upper())
                 if func:
                     result += '%s."%s", ' % (self.table_alias(), field.db_field_name)
                 else:
                     result += '%s, %s."%s", ' % (self.lookup_field_sql(field, db_module), self.table_alias(), field.db_field_name)
             else:
                 result += '%s."%s", ' % (self.table_alias(), field.db_field_name)
         if result:
             result = result[:-2]
             result = ' GROUP BY ' + result
         return result
     else:
         return ''
开发者ID:jam-py,项目名称:jam-py,代码行数:27,代码来源:sql.py


示例9: proxy

        def proxy(*children, **arguments):
            buffer = "<" + tag
            for key, value in iteritems(arguments):
                if value is None:
                    continue
                if key[-1] == "_":
                    key = key[:-1]
                if key in self._boolean_attributes:
                    if not value:
                        continue
                    if self._dialect == "xhtml":
                        value = '="' + key + '"'
                    else:
                        value = ""
                else:
                    value = '="' + escape(value) + '"'
                buffer += " " + key + value
            if not children and tag in self._empty_elements:
                if self._dialect == "xhtml":
                    buffer += " />"
                else:
                    buffer += ">"
                return buffer
            buffer += ">"

            children_as_string = "".join([text_type(x) for x in children if x is not None])

            if children_as_string:
                if tag in self._plaintext_elements:
                    children_as_string = escape(children_as_string)
                elif tag in self._c_like_cdata and self._dialect == "xhtml":
                    children_as_string = "/*<![CDATA[*/" + children_as_string + "/*]]>*/"
            buffer += children_as_string + "</" + tag + ">"
            return buffer
开发者ID:211sandiego,项目名称:calllog211,代码行数:34,代码来源:utils.py


示例10: lists

    def lists(self):
        """Return a list of ``(key, values)`` pairs, where values is the list
        of all values associated with the key."""

        for key, values in iteritems(dict, self):
            values = [self.sanitize_input(v) for v in values]
            yield key, values
开发者ID:SUNET,项目名称:eduid-common,代码行数:7,代码来源:request.py


示例11: dump_header

def dump_header(iterable, allow_token=True):
    """Dump an HTTP header again.  This is the reversal of
    :func:`parse_list_header`, :func:`parse_set_header` and
    :func:`parse_dict_header`.  This also quotes strings that include an
    equals sign unless you pass it as dict of key, value pairs.

    >>> dump_header({'foo': 'bar baz'})
    'foo="bar baz"'
    >>> dump_header(('foo', 'bar baz'))
    'foo, "bar baz"'

    :param iterable: the iterable or dict of values to quote.
    :param allow_token: if set to `False` tokens as values are disallowed.
                        See :func:`quote_header_value` for more details.
    """
    if isinstance(iterable, dict):
        items = []
        for key, value in iteritems(iterable):
            if value is None:
                items.append(key)
            else:
                items.append('%s=%s' % (
                    key,
                    quote_header_value(value, allow_token=allow_token)
                ))
    else:
        items = [quote_header_value(x, allow_token=allow_token)
                 for x in iterable]
    return ', '.join(items)
开发者ID:211sandiego,项目名称:calllog211,代码行数:29,代码来源:http.py


示例12: find_actions

def find_actions(namespace, action_prefix):
    """Find all the actions in the namespace."""
    actions = {}
    for key, value in iteritems(namespace):
        if key.startswith(action_prefix):
            actions[key[len(action_prefix):]] = analyse_action(value)
    return actions
开发者ID:sherrycherish,项目名称:qiubai,代码行数:7,代码来源:script.py


示例13: __call__

 def __call__(self, environ, start_response):
     path = environ['PATH_INFO']
     app = self.app
     for prefix, opts in iteritems(self.targets):
         if path.startswith(prefix):
             app = self.proxy_to(opts, path, prefix)
             break
     return app(environ, start_response)
开发者ID:AlerzDev,项目名称:Brazo-Proyecto-Final,代码行数:8,代码来源:wsgi.py


示例14: _find_exceptions

def _find_exceptions():
    for name, obj in iteritems(globals()):
        try:
            if getattr(obj, 'code', None) is not None:
                default_exceptions[obj.code] = obj
                __all__.append(obj.__name__)
        except TypeError: # pragma: no cover
            continue
开发者ID:wjreichard,项目名称:nrgRetail.api,代码行数:8,代码来源:exceptions.py


示例15: recreate

 def recreate(comp):
     for key, (old_field, new_field) in iteritems(comp):
         if old_field and new_field:
             if old_field['field_name'] != new_field['field_name']:
                 return True
             elif old_field['default_value'] != new_field['default_value']:
                 return True
         elif old_field and not new_field:
             return True
开发者ID:jam-py,项目名称:jam-py,代码行数:9,代码来源:sql.py


示例16: prepare_environ_pickle

def prepare_environ_pickle(environ):
    result = {}
    for key, value in iteritems(environ):
        try:
            pickle.dumps((key, value))
        except Exception:
            continue
        result[key] = value
    return result
开发者ID:tsampi,项目名称:tsampi-0,代码行数:9,代码来源:test_wrappers.py


示例17: __init__

 def __init__(self, app, targets, chunk_size=2 << 13, timeout=10):
     def _set_defaults(opts):
         opts.setdefault('remove_prefix', False)
         opts.setdefault('host', '<auto>')
         opts.setdefault('headers', {})
         opts.setdefault('ssl_context', None)
         return opts
     self.app = app
     self.targets = dict(('/%s/' % k.strip('/'), _set_defaults(v))
                         for k, v in iteritems(targets))
     self.chunk_size = chunk_size
     self.timeout = timeout
开发者ID:AlerzDev,项目名称:Brazo-Proyecto-Final,代码行数:12,代码来源:wsgi.py


示例18: unserialize

    def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        if isinstance(string, text_type):
            string = string.encode('utf-8', 'replace')
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('utf-8', 'replace')
        try:
            base64_hash, data = string.split(b'?', 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split(b'&'):
                mac.update(b'|' + item)
                if not b'=' in item:
                    items = None
                    break
                key, value = item.split(b'=', 1)
                # try to make the key a string
                key = url_unquote_plus(key.decode('ascii'))
                try:
                    key = to_native(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64.b64decode(base64_hash)
            except TypeError:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in iteritems(items):
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if '_expires' in items:
                        if time() > items['_expires']:
                            items = ()
                        else:
                            del items['_expires']
            else:
                items = ()
        return cls(items, secret_key, False)
开发者ID:parker1333752,项目名称:svc_analyzer,代码行数:53,代码来源:securecookie.py


示例19: __call__

    def __call__(self, environ, start_response):
        cleaned_path = get_path_info(environ)
        if PY2:
            cleaned_path = cleaned_path.encode(sys.getfilesystemencoding())
        # sanitize the path for non unix systems
        cleaned_path = cleaned_path.strip('/')
        for sep in os.sep, os.altsep:
            if sep and sep != '/':
                cleaned_path = cleaned_path.replace(sep, '/')
        path = '/' + '/'.join(x for x in cleaned_path.split('/')
                              if x and x != '..')
        file_loader = None
        for search_path, loader in iteritems(self.exports):
            if search_path == path:
                real_filename, file_loader = loader(None)
                if file_loader is not None:
                    break
            if not search_path.endswith('/'):
                search_path += '/'
            if path.startswith(search_path):
                real_filename, file_loader = loader(path[len(search_path):])
                if file_loader is not None:
                    break
        if file_loader is None or not self.is_allowed(real_filename):
            return self.app(environ, start_response)

        guessed_type = mimetypes.guess_type(real_filename)
        mime_type = guessed_type[0] or self.fallback_mimetype
        f, mtime, file_size = file_loader()

        headers = [('Date', http_date())]
        if self.cache:
            timeout = self.cache_timeout
            etag = self.generate_etag(mtime, file_size, real_filename)
            headers += [
                ('Etag', '"%s"' % etag),
                ('Cache-Control', 'max-age=%d, public' % timeout)
            ]
            if not is_resource_modified(environ, etag, last_modified=mtime):
                f.close()
                start_response('304 Not Modified', headers)
                return []
            headers.append(('Expires', http_date(time() + timeout)))
        else:
            headers.append(('Cache-Control', 'public'))

        headers.extend((
            ('Content-Type', mime_type),
            ('Content-Length', str(file_size)),
            ('Last-Modified', http_date(mtime))
        ))
        start_response('200 OK', headers)
        return wrap_file(environ, f)
开发者ID:0x00xw,项目名称:wooyun,代码行数:53,代码来源:wsgi.py


示例20: _find_exceptions

def _find_exceptions():
    for name, obj in iteritems(globals()):
        try:
            is_http_exception = issubclass(obj, HTTPException)
        except TypeError:
            is_http_exception = False
        if not is_http_exception or obj.code is None:
            continue
        __all__.append(obj.__name__)
        old_obj = default_exceptions.get(obj.code, None)
        if old_obj is not None and issubclass(obj, old_obj):
            continue
        default_exceptions[obj.code] = obj
开发者ID:DaTrollMon,项目名称:werkzeug,代码行数:13,代码来源:exceptions.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python _compat.iterkeys函数代码示例发布时间:2022-05-26
下一篇:
Python werkzeug.Response类代码示例发布时间: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