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

Python six.viewitems函数代码示例

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

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



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

示例1: setMetadata

    def setMetadata(self, folder, metadata):
        """
        Set metadata on a folder.  A `ValidationException` is thrown in the
        cases where the metadata JSON object is badly formed, or if any of the
        metadata keys contains a period ('.').

        :param folder: The folder to set the metadata on.
        :type folder: dict
        :param metadata: A dictionary containing key-value pairs to add to
                     the folder's meta field
        :type metadata: dict
        :returns: the folder document
        """
        if 'meta' not in folder:
            folder['meta'] = {}

        # Add new metadata to existing metadata
        folder['meta'].update(six.viewitems(metadata))

        # Remove metadata fields that were set to null (use items in py3)
        folder['meta'] = {k: v
                          for k, v in six.viewitems(folder['meta'])
                          if v is not None}

        folder['updated'] = datetime.datetime.utcnow()

        # Validate and save the item
        return self.save(folder)
开发者ID:chapmanbe,项目名称:girder,代码行数:28,代码来源:folder.py


示例2: validate_southbound_devices_usages

def validate_southbound_devices_usages(nets, ni):
    kernel_config = KernelConfig(ni)

    for requested_net, net_info in six.viewitems(nets):
        if 'remove' in net_info:
            kernel_config.removeNetwork(requested_net)

    for requested_net, net_info in six.viewitems(nets):
        if 'remove' in net_info:
            continue
        kernel_config.setNetwork(requested_net, net_info)

    underlying_devices = []
    for net_name, net_attrs in six.viewitems(kernel_config.networks):
        vlan = net_attrs.get('vlan')
        if 'bonding' in net_attrs:
            underlying_devices.append((net_attrs['bonding'], vlan))
        elif 'nic' in net_attrs:
            underlying_devices.append((net_attrs['nic'], vlan))
        else:
            if not net_attrs['bridged']:
                raise ne.ConfigNetworkError(
                    ne.ERR_BAD_PARAMS,
                    'southbound device not specified for non-bridged '
                    'network "{}"'.format(net_name))

    if len(set(underlying_devices)) < len(underlying_devices):
        raise ne.ConfigNetworkError(
            ne.ERR_BAD_PARAMS,
            'multiple networks/similar vlans cannot be'
            ' defined on a single underlying device. '
            'kernel networks: {}\nrequested networks: {}'.format(
                kernel_config.networks,
                nets))
开发者ID:nirs,项目名称:vdsm,代码行数:34,代码来源:validator.py


示例3: testUploadFileToFolder

    def testUploadFileToFolder(self):
        filepath = os.path.join(self.libTestDir, 'sub0', 'f')

        stream_filename = 'uploaded_from_stream'
        disk_filename = 'uploaded_from_disk'

        # upload filepath as a stream and as a local file, and assert the end result is the same
        with open(filepath, 'rb') as infile:
            infile.seek(0, os.SEEK_END)
            size = infile.tell()
            infile.seek(0)

            self.client.uploadStreamToFolder(str(self.publicFolder['_id']), infile, stream_filename,
                                             size, mimeType='text/plain')

        self.client.uploadFileToFolder(str(self.publicFolder['_id']), filepath,
                                       filename=disk_filename)

        stream_item = six.next(self.client.listItem(str(self.publicFolder['_id']),
                                                    name=stream_filename))
        disk_item = six.next(self.client.listItem(str(self.publicFolder['_id']),
                                                  name=disk_filename))

        # assert names and sizes are correct
        self.assertEqual(stream_filename, stream_item['name'])
        self.assertEqual(size, stream_item['size'])
        self.assertEqual(disk_filename, disk_item['name'])
        self.assertEqual(size, disk_item['size'])

        # assert every other field (besides unique ones) are identical
        unique_attrs = ('_id', 'name', 'created', 'updated')
        self.assertEqual({k: v for (k, v) in six.viewitems(stream_item) if k not in unique_attrs},
                         {k: v for (k, v) in six.viewitems(disk_item) if k not in unique_attrs})
开发者ID:girder,项目名称:girder,代码行数:33,代码来源:lib_test.py


示例4: setMetadata

    def setMetadata(self, folder, metadata, allowNull=False):
        """
        Set metadata on a folder.  A `ValidationException` is thrown in the
        cases where the metadata JSON object is badly formed, or if any of the
        metadata keys contains a period ('.').

        :param folder: The folder to set the metadata on.
        :type folder: dict
        :param metadata: A dictionary containing key-value pairs to add to
                     the folder's meta field
        :type metadata: dict
        :param allowNull: Whether to allow `null` values to be set in the item's
            metadata. If set to `False` or omitted, a `null` value will cause that
            metadata field to be deleted.
        :returns: the folder document
        """
        if 'meta' not in folder:
            folder['meta'] = {}

        # Add new metadata to existing metadata
        folder['meta'].update(six.viewitems(metadata))

        # Remove metadata fields that were set to null (use items in py3)
        if not allowNull:
            toDelete = [k for k, v in six.viewitems(metadata) if v is None]
            for key in toDelete:
                del folder['meta'][key]

        folder['updated'] = datetime.datetime.utcnow()

        self.validateKeys(folder['meta'])

        # Validate and save the item
        return self.save(folder)
开发者ID:adsorensen,项目名称:girder,代码行数:34,代码来源:folder.py


示例5: setMetadata

    def setMetadata(self, item, metadata):
        """
        Set metadata on an item.  A `ValidationException` is thrown in the
        cases where the metadata JSON object is badly formed, or if any of the
        metadata keys contains a period ('.').

        :param item: The item to set the metadata on.
        :type item: dict
        :param metadata: A dictionary containing key-value pairs to add to
                     the items meta field
        :type metadata: dict
        :returns: the item document
        """
        if 'meta' not in item:
            item['meta'] = {}

        # Add new metadata to existing metadata
        item['meta'].update(six.viewitems(metadata))

        # Remove metadata fields that were set to null (use items in py3)
        toDelete = [k for k, v in six.viewitems(item['meta']) if v is None]
        for key in toDelete:
            del item['meta'][key]

        item['updated'] = datetime.datetime.utcnow()

        # Validate and save the item
        return self.save(item)
开发者ID:kotfic,项目名称:girder,代码行数:28,代码来源:item.py


示例6: _set_networks_mtu

    def _set_networks_mtu(self, nets, sb_max_mtu_map):
        for net, netattrs in six.viewitems(nets):
            self._set_mtu(net, netattrs['mtu'])

        for sb, mtu in six.viewitems(sb_max_mtu_map):
            if mtu:
                self._set_mtu(sb, mtu)
开发者ID:nirs,项目名称:vdsm,代码行数:7,代码来源:switch.py


示例7: _filter_env

 def _filter_env(self, env):
     "return true if env match"
     if isinstance(env, dict):
         return viewitems(env) <= viewitems(self.environ)
     if isinstance(env, list):
         return bool([key for key in env if key in self.environ])
     return str(env) in self.environ
开发者ID:cmehay,项目名称:pyentrypoint,代码行数:7,代码来源:links.py


示例8: test_approval

def test_approval(sample_submitted_application):
    a = sample_submitted_application
    assert a.supplier is None
    sample_submitted_application.set_approval(True)
    assert a.supplier is not None

    product_query = Product.query.filter(Product.supplier_code == a.supplier.code)
    products = product_query.all()
    assert a.supplier.products == products

    product_from_submitted = a.data['products']['0']
    product_from_submitted['id'] = products[0].id
    product_from_submitted['supplier_code'] = a.supplier.code
    product_from_submitted['links'] = {
        'self': '/products/{}'.format(products[0].id)
    }

    assert a.supplier.serializable['products'] == [product_from_submitted]
    assert 'recruitment' in a.supplier.serializable['seller_types']
    assert a.supplier.is_recruiter

    r_info = a.supplier.domains[0].recruiter_info._fieldsdict
    r_info_from_application = a.data['recruiter_info']['Strategy and Policy']

    assert six.viewitems(r_info) >= six.viewitems(r_info_from_application)

    assert six.viewitems(a.supplier.serializable['recruiter_info']) <= \
        six.viewitems(a.data['recruiter_info'])
开发者ID:AusDTO,项目名称:dto-digitalmarketplace-api,代码行数:28,代码来源:test_application.py


示例9: wsgi_handler

 def wsgi_handler(env, start_response):
     if headers:
         # For Python 2.6 which does not have viewitems
         if six.PY2:
             env >= headers
         else:
             assert six.viewitems(env) >= six.viewitems(headers)
     assert body == env['wsgi.input'].read()
     start_response('200 OK', [])
     return []
开发者ID:jonozzz,项目名称:geventhttpclient,代码行数:10,代码来源:test_useragent.py


示例10: order_networks

def order_networks(networks):
    vlanned_nets = ((net, attr) for net, attr in six.viewitems(networks)
                    if 'vlan'in attr)
    non_vlanned_nets = ((net, attr) for net, attr in six.viewitems(networks)
                        if 'vlan'not in attr)

    for net, attr in vlanned_nets:
        yield net, attr
    for net, attr in non_vlanned_nets:
        yield net, attr
开发者ID:oVirt,项目名称:vdsm,代码行数:10,代码来源:legacy_switch.py


示例11: _add_speed_device_info

def _add_speed_device_info(net_caps):
    """Collect and include device speed information in the report."""
    timeout = 2
    for devname, devattr in six.viewitems(net_caps['nics']):
        timeout -= _wait_for_link_up(devname, timeout)
        devattr['speed'] = nic.speed(devname)

    for devname, devattr in six.viewitems(net_caps['bondings']):
        timeout -= _wait_for_link_up(devname, timeout)
        devattr['speed'] = bond.speed(devname)
开发者ID:nirs,项目名称:vdsm,代码行数:10,代码来源:configurator.py


示例12: _update_running_config

def _update_running_config(networks, bonds):
    """
    Recreate RunningConfig so that following setSafeNetworkConfig
    will persist a valid configuration.
    """
    running_config = RunningConfig()
    for net, net_attr in six.viewitems(networks):
        running_config.setNetwork(net, net_attr)
    for bonding, bonding_attr in six.viewitems(bonds):
        running_config.setBonding(bonding, bonding_attr)
    running_config.save()
开发者ID:nirs,项目名称:vdsm,代码行数:11,代码来源:restore_net_config.py


示例13: test_creates_sentry_app

    def test_creates_sentry_app(self):
        self.login_as(user=self.user)

        response = self._post()
        expected = {
            'name': 'MyApp',
            'scopes': ['project:read', 'project:write'],
            'webhook_url': 'https://example.com',
        }

        assert response.status_code == 201, response.content
        assert six.viewitems(expected) <= six.viewitems(response.data)
开发者ID:alexandrul,项目名称:sentry,代码行数:12,代码来源:test_sentry_apps.py


示例14: _normalize_net_ifcfg_keys

def _normalize_net_ifcfg_keys(networks):
    """
    Ignore keys in persisted networks that might originate from vdsm-reg.
    these might be a result of calling setupNetworks with ifcfg values
    that come from the original interface that is serving the management
    network. for 3.5, VDSM still supports passing arbitrary values
    directly to the ifcfg files, e.g. 'IPV6_AUTOCONF=no'.
    We filter them out here since they are not supported anymore.
    """
    for netname, netattrs in six.viewitems(networks):
        networks[netname] = {k: v for k, v in six.viewitems(netattrs)
                             if not _is_unsupported_ifcfg_key(k)}
开发者ID:EdDev,项目名称:vdsm,代码行数:12,代码来源:netupgrade.py


示例15: stringify

        def stringify(node, indent=0, tab='  '):
            data = (k for k, v in six.viewitems(node) if not isinstance(v, trie))
            result = []
            for k in data:
                result.append("{:s}{!r} -> {!r}".format(tab * indent, k, node[k]))

            branches = [k for k, v in six.viewitems(node) if isinstance(v, trie)]
            for k in branches:
                result.append("{:s}{!r}".format(tab * indent, k))
                branch_data = stringify(node[k], indent+1, tab=tab)
                result.extend(branch_data)
            return result
开发者ID:arizvisa,项目名称:idascripts,代码行数:12,代码来源:_comment.py


示例16: wrapped

        def wrapped(*args, **kwargs):
            model = self.model(self.modelName, self.plugin)

            for raw, converted in six.viewitems(self.map):
                id = self._getIdValue(kwargs, raw)

                if self.force:
                    kwargs[converted] = model.load(
                        id, force=True, **self.kwargs)
                elif self.level is not None:
                    kwargs[converted] = model.load(
                        id=id, level=self.level, user=getCurrentUser(),
                        **self.kwargs)
                else:
                    kwargs[converted] = model.load(id, **self.kwargs)

                if kwargs[converted] is None and self.exc:
                    raise RestException(
                        'Invalid %s id (%s).' % (model.name, str(id)))

                if self.requiredFlags:
                    model.requireAccessFlags(
                        kwargs[converted], user=getCurrentUser(), flags=self.requiredFlags)

            return fun(*args, **kwargs)
开发者ID:data-exp-lab,项目名称:girder,代码行数:25,代码来源:rest.py


示例17: requireParams

    def requireParams(self, required, provided=None):
        """
        This method has two modes. In the first mode, this takes two
        parameters, the first being a required parameter or list of
        them, and the second the dictionary of parameters that were
        passed. If the required parameter does not appear in the
        passed parameters, a ValidationException is raised.

        The second mode of operation takes only a single
        parameter, which is a dict mapping required parameter names
        to passed in values for those params. If the value is ``None``,
        a ValidationException is raised. This mode works well in conjunction
        with the ``autoDescribeRoute`` decorator, where the parameters are
        not all contained in a single dictionary.

        :param required: An iterable of required params, or if just one is
            required, you can simply pass it as a string.
        :type required: `list, tuple, or str`
        :param provided: The list of provided parameters.
        :type provided: dict
        """
        if provided is None and isinstance(required, dict):
            for name, val in six.viewitems(required):
                if val is None:
                    raise RestException('Parameter "%s" is required.' % name)
        else:
            if isinstance(required, six.string_types):
                required = (required,)

            for param in required:
                if provided is None or param not in provided:
                    raise RestException('Parameter "%s" is required.' % param)
开发者ID:data-exp-lab,项目名称:girder,代码行数:32,代码来源:rest.py


示例18: join_impl

def join_impl(other, join_type, sequence):
    """
    Implementation for join_t
    :param other: other sequence to join with
    :param join_type: join type (inner, outer, left, right)
    :param sequence: first sequence to join with
    :return: joined sequence
    """
    if join_type == "inner":
        return inner_join_impl(other, sequence)
    seq_dict = {}
    for element in sequence:
        seq_dict[element[0]] = element[1]
    seq_kv = seq_dict
    other_kv = dict(other)
    if join_type == "left":
        keys = seq_kv.keys()
    elif join_type == "right":
        keys = other_kv.keys()
    elif join_type == "outer":
        keys = set(list(seq_kv.keys()) + list(other_kv.keys()))
    else:
        raise TypeError("Wrong type of join specified")
    result = {}
    for k in keys:
        result[k] = (seq_kv.get(k), other_kv.get(k))
    return six.viewitems(result)
开发者ID:yenchih,项目名称:ScalaFunctional,代码行数:27,代码来源:transformations.py


示例19: get_id_by_external

    def get_id_by_external(self, **kwargs):
        """Search tmdb for a show, using an external id.

        Accepts as kwargs, so you'l need to add the externals as key/values.
        :param tvrage_id: The tvrage id.
        :param tvdb_id: The tvdb id.
        :param imdb_id: An imdb id (inc. tt).
        :returns: A dict with externals, including the tvmaze id.
        """
        try:
            wanted_externals = ['tvdb_id', 'imdb_id', 'tvrage_id']
            for external_id in wanted_externals:
                if kwargs.get(external_id):
                    result = self.tmdb.Find(kwargs.get(external_id)).info(**{'external_source': external_id})
                    if result.get('tv_results') and result['tv_results'][0]:
                        # Get the external id's for the passed shows id.
                        externals = self.tmdb.TV(result['tv_results'][0]['id']).external_ids()
                        externals = {tmdb_external_id: external_value
                                     for tmdb_external_id, external_value
                                     in viewitems(externals)
                                     if external_value and tmdb_external_id in wanted_externals}
                        externals['tmdb_id'] = result['tv_results'][0]['id']
                        return externals
            return {}
        except RequestException as error:
            raise IndexerException("Could not get external id's. Cause: {cause}".format(cause=error))
开发者ID:pymedusa,项目名称:SickRage,代码行数:26,代码来源:tmdb.py


示例20: _remove_zero_values_in_net_qos

def _remove_zero_values_in_net_qos(net_qos):
    """
    net_qos = {'out': {
            'ul': {'m1': 0, 'd': 0, 'm2': 8000000},
            'ls': {'m1': 4000000, 'd': 100000, 'm2': 3000000}}}
    stripped_qos = {'out': {
            'ul': {'m2': 8000000},
            'ls': {'m1': 4000000, 'd': 100000, 'm2': 3000000}}}"""
    stripped_qos = {}
    for part, part_config in six.viewitems(net_qos):
        stripped_qos[part] = dict(part_config)  # copy
        for curve, curve_config in six.viewitems(part_config):
            stripped_qos[part][curve] = dict((k, v) for k, v
                                             in six.viewitems(curve_config)
                                             if v != 0)
    return stripped_qos
开发者ID:EdDev,项目名称:vdsm,代码行数:16,代码来源:kernelconfig.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python six.viewkeys函数代码示例发布时间:2022-05-27
下一篇:
Python six.unicode函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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