当前位置: 首页>>代码示例>>Python>>正文


Python toml.dumps函数代码示例

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


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

示例1: write

async def write(store, media_dir):
    global prev
    state = store.state
    user_state = state['app']['user']
    books = user_state['books']
    selected_book = user_state['current_book']
    selected_lang = user_state['current_language']
    if selected_book != prev['current_book']:
        if not selected_book == manual_filename:
            selected_book = os.path.relpath(selected_book, media_dir)
        s = toml.dumps({'current_book': selected_book,
                        'current_language': selected_lang})
        path = os.path.join(media_dir, 'sd-card', USER_STATE_FILE)
        async with aiofiles.open(path, 'w') as f:
            await f.write(s)
    for filename in books:
        book = books[filename]
        if filename in prev['books']:
            prev_book = prev['books'][filename]
        else:
            prev_book = BookFile()
        if book.page_number != prev_book.page_number or book.bookmarks != prev_book.bookmarks:
            path = to_state_file(book.filename)
            if book.filename == manual_filename:
                path = os.path.join(media_dir, path)
            bms = [bm + 1 for bm in book.bookmarks if bm != 'deleted']
            # remove start-of-book and end-of-book bookmarks
            bms = bms[1:-1]
            # ordered to make sure current_page comes before bookmarks
            d = OrderedDict([['current_page', book.page_number + 1],
                             ['bookmarks', bms]])
            s = toml.dumps(d)
            async with aiofiles.open(path, 'w') as f:
                await f.write(s)
    prev = user_state
开发者ID:Bristol-Braille,项目名称:canute-ui,代码行数:35,代码来源:initial_state.py

示例2: _parse_pipfile

    def _parse_pipfile(self, contents):
        # If any outline tables are present...
        if ("[packages." in contents) or ("[dev-packages." in contents):
            data = toml.loads(contents)
            # Convert all outline tables to inline tables.
            for section in ("packages", "dev-packages"):
                for package in data.get(section, {}):
                    # Convert things to inline tables — fancy :)
                    if hasattr(data[section][package], "keys"):
                        _data = data[section][package]
                        data[section][package] = toml._get_empty_inline_table(dict)
                        data[section][package].update(_data)
            # We lose comments here, but it's for the best.)
            try:
                return contoml.loads(toml.dumps(data, preserve=True))

            except RuntimeError:
                return toml.loads(toml.dumps(data, preserve=True))

        else:
            # Fallback to toml parser, for large files.
            try:
                return contoml.loads(contents)

            except Exception:
                return toml.loads(contents)
开发者ID:TimexStudio,项目名称:pipenv,代码行数:26,代码来源:project.py

示例3: parsed_pipfile

    def parsed_pipfile(self):
        # Open the pipfile, read it into memory.
        with open(self.pipfile_location) as f:
            contents = f.read()

        # If any outline tables are present...
        if ('[packages.' in contents) or ('[dev-packages.' in contents):

            data = toml.loads(contents)

            # Convert all outline tables to inline tables.
            for section in ('packages', 'dev-packages'):
                for package in data.get(section, {}):

                    # Convert things to inline tables — fancy :)
                    if hasattr(data[section][package], 'keys'):
                        _data = data[section][package]
                        data[section][package] = toml._get_empty_inline_table(dict)
                        data[section][package].update(_data)

            # We lose comments here, but it's for the best.)
            try:
                return contoml.loads(toml.dumps(data, preserve=True))
            except RuntimeError:
                return toml.loads(toml.dumps(data, preserve=True))

        else:
            # Fallback to toml parser, for large files.
            try:
                return contoml.loads(contents)
            except Exception:
                return toml.loads(contents)
开发者ID:cogzidel,项目名称:healthchecks,代码行数:32,代码来源:project.py

示例4: create_config

    def create_config(self):
        bgp_config = {'Global': {'GlobalConfig': {'As': self.asn, 'RouterId': self.router_id}}}
        for peer, info in self.peers.iteritems():
            if self.asn == peer.asn:
                peer_type = self.PEER_TYPE_INTERNAL
            else:
                peer_type = self.PEER_TYPE_EXTERNAL

            afi_safi_list = []
            version = netaddr.IPNetwork(info['neigh_addr']).version
            if version == 4:
                afi_safi_list.append({'AfiSafiName': 'ipv4-unicast'})
            elif version == 6:
                afi_safi_list.append({'AfiSafiName': 'ipv6-unicast'})
            else:
                Exception('invalid ip address version. {0}'.format(version))

            if info['evpn']:
                afi_safi_list.append({'AfiSafiName': 'l2vpn-evpn'})

            n = {'NeighborConfig':
                    {'NeighborAddress': info['neigh_addr'].split('/')[0],
                     'PeerAs': peer.asn,
                     'AuthPassword': info['passwd'],
                     'PeerType': peer_type,
                    },
                 'AfiSafis': {'AfiSafiList': afi_safi_list}
                }

            if info['passive']:
                n['TransportOptions'] = {'PassiveMode':True}

            if info['is_rs_client']:
                n['RouteServer'] = {'RouteServerClient': True}

            if 'Neighbors' not in bgp_config:
                bgp_config['Neighbors'] = {'NeighborList': []}

            bgp_config['Neighbors']['NeighborList'].append(n)

        dplane_config = {'Type': 'netlink', 'VirtualNetworkList': []}
        for info in self.vns:
            dplane_config['VirtualNetworkList'].append({'RD': '{0}:{1}'.format(self.asn, info['vni']),
                                                        'VNI': info['vni'],
                                                        'VxlanPort': info['vxlan_port'],
                                                        'VtepInterface': info['vtep'],
                                                        'Etag': info['color'],
                                                        'SniffInterfaces': info['member'],
                                                        'MemberInterfaces': info['member']})

        config = {'Bgp': bgp_config, 'Dataplane': dplane_config}

        with open('{0}/goplaned.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow(toml.dumps(config))
            f.write(toml.dumps(config))
开发者ID:ttsubo,项目名称:goplane,代码行数:55,代码来源:demo.py

示例5: create_config

    def create_config(self):
        config = {'Global': {'As': self.asn, 'RouterId': self.router_id}}
        for peer, info in self.peers.iteritems():
            if self.asn == peer.asn:
                peer_type = self.PEER_TYPE_INTERNAL
            else:
                peer_type = self.PEER_TYPE_EXTERNAL

            afi_safi_list = []
            version = netaddr.IPNetwork(info['neigh_addr']).version
            if version == 4:
                afi_safi_list.append({'AfiSafiName': 'ipv4-unicast'})
            elif version == 6:
                afi_safi_list.append({'AfiSafiName': 'ipv6-unicast'})
            else:
                Exception('invalid ip address version. {0}'.format(version))

            if info['evpn']:
                afi_safi_list.append({'AfiSafiName': 'l2vpn-evpn'})
                afi_safi_list.append({'AfiSafiName': 'encap'})
                afi_safi_list.append({'AfiSafiName': 'rtc'})

            n = {'NeighborAddress': info['neigh_addr'].split('/')[0],
                 'PeerAs': peer.asn,
                 'AuthPassword': info['passwd'],
                 'PeerType': peer_type,
                 'AfiSafiList': afi_safi_list}

            if info['passive']:
                n['TransportOptions'] = {'PassiveMode': True}

            if info['is_rs_client']:
                n['RouteServer'] = {'RouteServerClient': True}

            if info['is_rr_client']:
                clusterId = info['cluster_id']
                n['RouteReflector'] = {'RouteReflectorClient': True,
                                       'RouteReflectorClusterId': clusterId}

            if 'NeighborList' not in config:
                config['NeighborList'] = []

            config['NeighborList'].append(n)

        with open('{0}/gobgpd.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow('[{0}\'s new config]'.format(self.name))
            print colors.yellow(indent(toml.dumps(config)))
            f.write(toml.dumps(config))
开发者ID:ttaanngg,项目名称:gobgp,代码行数:48,代码来源:gobgp.py

示例6: save_toml_file

def save_toml_file(data, path):
    try:
        formatted_data = unicode(toml.dumps(data))
        with io.open(path, "wt", encoding="utf-8") as f:
            f.write(formatted_data)
    except Exception:
        simple_log(True)
开发者ID:seekM,项目名称:caster,代码行数:7,代码来源:utilities.py

示例7: __init__

    def __init__(self, overrides=None, valgrind=False):
        self.pid = None
        with open(os.path.join(constants.ASSETS_DIR, "test.toml")) as fp:
            self.cf = toml.load(fp)
        if overrides:
            update_nested_dict(self.cf, overrides)
        self.cf["core"].pop("admin_host", None)
        # extract some field from cf
        self.data_store = self.cf["zone_source"]["type"].lower()
        self.pidfile = self.cf["core"]["pidfile"]
        self.admin_host = self.cf["core"].get("admin_host", None)
        self.admin_port = self.cf["core"].get("admin_port", None)
        self.dns_port = self.cf["core"]["port"]
        self.dns_host = self.cf["core"]["bind"]

        # override mongo host and mongo port
        mongo_conf = self.cf["zone_source"]["mongo"]
        if self.data_store == "mongo":
            self.zm = ZoneMongo(constants.MONGO_HOST,
                                constants.MONGO_PORT,
                                mongo_conf["dbname"])
        self.valgrind = valgrind

        self.cf_str = toml.dumps(self.cf)
        self.fp = tempfile.NamedTemporaryFile()
        self.fp.write(self.cf_str.encode("utf8"))
        self.fp.flush()
        fname = self.fp.name

        if self.valgrind:
            # TODO find the bug of possible lost and still reachable memory
            self.cmd = "valgrind --leak-check=full --show-reachable=no --show-possibly-lost=no %s -c %s" % (DNS_BIN, fname)
        else:
            self.cmd = "%s -c %s" % (DNS_BIN, fname)
        self.vagrant = vagrant.Vagrant(root=os.path.join(constants.REPO_ROOT, "vagrant"))
开发者ID:liweiwei05,项目名称:shuke,代码行数:35,代码来源:server.py

示例8: create_goplane_config

    def create_goplane_config(self):
        dplane_config = {'type': 'netlink', 'virtual-network-list': []}
        for info in self.vns:
            dplane_config['virtual-network-list'].append({'rd': '{0}:{1}'.format(self.asn, info['vni']),
                                                          'vni': info['vni'],
                                                          'vxlan-port': info['vxlan_port'],
                                                          'vtep-interface': info['vtep'],
                                                          'etag': info['color'],
                                                          'sniff-interfaces': info['member'],
                                                          'member-interfaces': info['member']})

        config = {'dataplane': dplane_config}

        with open('{0}/goplaned.conf'.format(self.config_dir), 'w') as f:
            print colors.yellow(toml.dumps(config))
            f.write(toml.dumps(config))
开发者ID:j-kato,项目名称:goplane,代码行数:16,代码来源:demo.py

示例9: config_wizard

def config_wizard():
    click.echo('''
You'll need to create a last.fm API application first. Do so here:

    http://www.last.fm/api/account/create

What you fill in doesn't matter at all, just make sure to save the API
Key and Shared Secret.
''')

    plex_scrobble = {
        'mediaserver_url': 'http://localhost:32400',
        'log_file': '/tmp/plex-scrobble.log',
        'cache_location': '/tmp/plex_scrobble.cache',
        'mediaserver_log_location': platform_log_directory()
    }

    config = {
        'lastfm': {
            key: click.prompt(key, type=str)
            for key in ['user_name', 'password', 'api_key', 'api_secret']
        }
    }

    config['plex-scrobble'] = {
        key: click.prompt(key, default=plex_scrobble[key])
        for key in plex_scrobble
    }

    generated = toml.dumps(config)
    click.echo('Generated config:\n\n%s' % generated)

    if click.confirm('Write to ~/.plex-scrobble.toml?'):
        with open(os.path.expanduser('~/.plex-scrobble.toml'), 'w') as fp:
            fp.write(generated)
开发者ID:jesseward,项目名称:plex-lastfm-scrobbler,代码行数:35,代码来源:__main__.py

示例10: _save_auth_keys

def _save_auth_keys(key_dict):
    """
    :param key_dict: auth parameters dict
    :type key_dict: dict
    :rtype: None
    """

    config_path = os.environ[constants.DCOS_CONFIG_ENV]
    toml_config = config.mutable_load_from_path(config_path)

    section = 'core'
    config_schema = json.loads(
        pkg_resources.resource_string(
            'dcoscli',
            'data/config-schema/core.json').decode('utf-8'))
    for k, v in iteritems(key_dict):
        python_value = jsonitem.parse_json_value(k, v, config_schema)
        name = '{}.{}'.format(section, k)
        toml_config[name] = python_value

    serial = toml.dumps(toml_config._dictionary)
    with util.open_file(config_path, 'w') as config_file:
        config_file.write(serial)

    return None
开发者ID:gismoranas,项目名称:dcos-cli,代码行数:25,代码来源:auth.py

示例11: write_toml

    def write_toml(self, data, path=None):
        """Writes the given data structure out as TOML."""
        if path is None:
            path = self.pipfile_location
        try:
            formatted_data = contoml.dumps(data).rstrip()
        except Exception:
            for section in ("packages", "dev-packages"):
                for package in data.get(section, {}):
                    # Convert things to inline tables — fancy :)
                    if hasattr(data[section][package], "keys"):
                        _data = data[section][package]
                        data[section][package] = toml._get_empty_inline_table(dict)
                        data[section][package].update(_data)
            formatted_data = toml.dumps(data).rstrip()

        if Path(path).absolute() == Path(self.pipfile_location).absolute():
            newlines = self._pipfile_newlines
        else:
            newlines = DEFAULT_NEWLINES
        formatted_data = cleanup_toml(formatted_data)
        with io.open(path, "w", newline=newlines) as f:
            f.write(formatted_data)
        # pipfile is mutated!
        self.clear_pipfile_cache()
开发者ID:TimexStudio,项目名称:pipenv,代码行数:25,代码来源:project.py

示例12: do_init

    def do_init(cwd: Path, pwd: Optional[Path], name: str, url: str,
                timezone: Optional[str], force: bool,
                config_fname: str=CONFIG_FNAME) -> Result[None]:
        """Initializes a new project.

        This function may overwrite any preexisting files and or directories
        in the target working directory.

        :param pathlib.path cwd: Path to the invocation directory.
        :param pathlib.path pwd: Path to the project directory to be created.
        :param str name: Name of the static site, to be put inside the
            generated config file.
        :param str url: URL of the static site, to be put inside the generated
            config file.
        :param str timezone: Geographical timezone name for timestamp-related
            values, to be put inside the generated config file.
        :param bool force: Whether to force project creation in nonempty
            directories or not.
        :param str config_name: Name of the config file to generate.
        :returns: Nothing upon successful execution or an error message when
            execution fails.
        :rtype: :class:`Result`.

        """
        name = pwd.name if (not name and pwd is not None) else name
        pwd = cwd if pwd is None else cwd.joinpath(pwd)
        try:
            pwd.mkdir(parents=True, exist_ok=True)
        except OSError as e:
            return Result.as_failure(e.strerror)

        if not force and any(True for _ in pwd.iterdir()):
            return Result.as_failure(
                "target project directory is not empty -- use the `-f` flag to"
                " force init in nonempty directories")

        rtz = get_tz(timezone)
        if rtz.is_failure:
            return rtz

        # Bootstrap directories.
        bootstrap_conf = SiteConfig(cwd, pwd, timezone=rtz.data)
        try:
            for dk in ("contents_src", "templates_src", "assets_src"):
                bootstrap_conf[dk].mkdir(parents=True, exist_ok=True)
        except OSError as e:
            return Result.as_failure(e.strerror)

        # Create initial TOML config file.
        init_conf = OrderedDict([
            ("site", OrderedDict([
                ("name", name or ""),
                ("url", url or ""),
                ("timezone", rtz.data.zone),
            ]))
        ])
        pwd.joinpath(config_fname).write_text(toml.dumps(init_conf))

        return Result.as_success(None)
开发者ID:bow,项目名称:volt,代码行数:59,代码来源:cli.py

示例13: serialize

	def serialize(self):
		d = {
			'general': {
				'measured_edge': self.__edge,
				'no_defect': self.__no_defect,
			},
		}
		return toml.dumps(d)
开发者ID:ExpHP,项目名称:defect,代码行数:8,代码来源:config.py

示例14: _set_config

def _set_config(name, value):
    with open(_get_config_file(), "r+") as f:
        config = toml.loads(f.read())
        config[name] = value
        new_conf = toml.dumps(config)
        f.truncate(0)
        f.seek(0)
        f.write(new_conf)
开发者ID:queirozfcom,项目名称:jekyll-utils,代码行数:8,代码来源:configs.py

示例15: save

    def save(self):
        if self._data is None:
            return

        with atomic_save(self._path) as outfp:
            self._data.prune()
            data = toml.dumps(self._data.to_dict()).encode("utf8")
            outfp.write(data)
开发者ID:wurstfabrik,项目名称:wurst-cli,代码行数:8,代码来源:conf.py


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