本文整理汇总了Python中tomlkit.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python tomlkit.dumps方法的具体用法?Python tomlkit.dumps怎么用?Python tomlkit.dumps使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tomlkit
的用法示例。
在下文中一共展示了tomlkit.dumps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def load(cls, f, encoding=None):
# type: (Any, Text) -> PipfileLoader
content = f.read()
if encoding is not None:
content = content.decode(encoding)
_data = tomlkit.loads(content)
should_reload = "source" not in _data
_data = reorder_source_keys(_data)
if should_reload:
if "sources" in _data:
content = tomlkit.dumps(_data)
else:
# HACK: There is no good way to prepend a section to an existing
# TOML document, but there's no good way to copy non-structural
# content from one TOML document to another either. Modify the
# TOML content directly, and load the new in-memory document.
sep = "" if content.startswith("\n") else "\n"
content = plette.pipfiles.DEFAULT_SOURCE_TOML + sep + content
data = tomlkit.loads(content)
data = cls.ensure_package_sections(data)
instance = cls(data)
instance._data = dict(instance._data)
return instance
示例2: save
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def save(config: Config, _path: str) -> None:
"""Saves the given config to the given path as a TOML file."""
if not isinstance(config, tomlkit.toml_document.TOMLDocument):
raise TypeError("Only tomlkit saving is supported for now")
path = Path(_path)
tmp_path = path.with_suffix(path.suffix + ".tmp")
done = False
config_data = tomlkit.dumps(config)
try:
with tmp_path.open("w+") as f:
f.write(config_data)
f.flush()
os.fsync(f.fileno())
tmp_path.replace(path)
done = True
finally:
if not done:
tmp_path.unlink()
# Source: https://stackoverflow.com/a/3233356
示例3: test_parsed_document_are_properly_json_representable
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def test_parsed_document_are_properly_json_representable(
example, json_example, example_name
):
doc = json.loads(json.dumps(parse(example(example_name)), default=json_serial))
json_doc = json.loads(json_example(example_name))
assert doc == json_doc
示例4: test_original_string_and_dumped_string_are_equal
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def test_original_string_and_dumped_string_are_equal(example, example_name):
content = example(example_name)
parsed = parse(content)
assert content == dumps(parsed)
示例5: test_a_raw_dict_can_be_dumped
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def test_a_raw_dict_can_be_dumped():
s = dumps({"foo": "bar"})
assert s == 'foo = "bar"\n'
示例6: test_write_backslash
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def test_write_backslash():
d = {"foo": "\e\u25E6\r"}
expected = """foo = "\\\\e\u25E6\\r"
"""
assert expected == dumps(d)
assert loads(dumps(d))["foo"] == "\e\u25E6\r"
示例7: dumps
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def dumps(self, reqs, project: RootDependency, content=None) -> str:
doc = document()
deps = []
for req in reqs:
deps.append(self._format_req(req=req))
doc['build-system']['requires'] = deps
return dumps(doc)
示例8: generate_poetry_content
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def generate_poetry_content(self):
template = POETRY_DEFAULT
if self._license:
template = POETRY_WITH_LICENSE
content = loads(template)
poetry_content = content["tool"]["poetry"]
poetry_content["name"] = self._project
poetry_content["version"] = self._version
poetry_content["description"] = self._description
poetry_content["authors"].append(self._author)
if self._license:
poetry_content["license"] = self._license
poetry_content["dependencies"]["python"] = self._python
for dep_name, dep_constraint in self._dependencies.items():
poetry_content["dependencies"][dep_name] = dep_constraint
for dep_name, dep_constraint in self._dev_dependencies.items():
poetry_content["dev-dependencies"][dep_name] = dep_constraint
# Add build system
build_system = table()
build_system_version = ">=" + BUILD_SYSTEM_MIN_VERSION
if BUILD_SYSTEM_MAX_VERSION is not None:
build_system_version += ",<" + BUILD_SYSTEM_MAX_VERSION
build_system.add("requires", ["poetry" + build_system_version])
build_system.add("build-backend", "poetry.masonry.api")
content.add("build-system", build_system)
return dumps(content)
示例9: write_lockfile
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def write_lockfile(self, toml_data: Container, show_message: bool = True) -> None:
toml_data.update({"root": self.get_project_metadata()})
with atomic_open_for_write(self.lockfile_file) as fp:
fp.write(tomlkit.dumps(toml_data))
if show_message:
stream.echo("Changes are written to pdm.lock.")
self._lockfile = None
示例10: get_content_hash
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def get_content_hash(self, algo: str = "md5") -> str:
# Only calculate sources and dependencies sections. Otherwise lock file is
# considered as unchanged.
dump_data = {"sources": self.tool_settings.get("source", [])}
for section in self.iter_sections():
toml_section = (
"dependencies" if section == "default" else f"{section}-dependencies"
)
dump_data[toml_section] = dict(self.tool_settings.get(toml_section, {}))
pyproject_content = json.dumps(dump_data, sort_keys=True)
hasher = hashlib.new(algo)
hasher.update(pyproject_content.encode("utf-8"))
return hasher.hexdigest()
示例11: write_pyproject
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def write_pyproject(self, show_message: bool = True) -> None:
with atomic_open_for_write(
self.pyproject_file.as_posix(), encoding="utf-8"
) as f:
f.write(tomlkit.dumps(self.pyproject))
if show_message:
stream.echo("Changes are written to pyproject.toml.")
self._pyproject = None
示例12: _save_config
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def _save_config(self) -> None:
"""Save the changed to config file."""
self._config_file.parent.mkdir(parents=True, exist_ok=True)
toml_data = {}
for key, value in self._file_data.items():
*parts, last = key.split(".")
temp = toml_data
for part in parts:
temp = temp.setdefault(part, {})
temp[last] = value
with self._config_file.open("w", encoding="utf-8") as fp:
fp.write(tomlkit.dumps(toml_data))
示例13: test_dump_nonascii_string
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def test_dump_nonascii_string():
content = u'name = "Stažené"\n'
toml_content = tomlkit.dumps(tomlkit.loads(content))
assert toml_content == content
示例14: write_toml
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def write_toml(self, data, path=None):
"""Writes the given data structure out as TOML."""
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
document = tomlkit.document()
for section in ("packages", "dev-packages"):
document[section] = tomlkit.table()
# Convert things to inline tables — fancy :)
for package in data.get(section, {}):
if hasattr(data[section][package], "keys"):
table = tomlkit.inline_table()
table.update(data[section][package])
document[section][package] = table
else:
document[section][package] = tomlkit.string(data[section][package])
formatted_data = tomlkit.dumps(document).rstrip()
if (
vistir.compat.Path(path).absolute()
== vistir.compat.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()
示例15: get_hash
# 需要导入模块: import tomlkit [as 别名]
# 或者: from tomlkit import dumps [as 别名]
def get_hash(self):
data = {
"_meta": {
"sources": self._data["source"],
"requires": self._data.get("requires", {}),
},
"default": self._data.get("packages", {}),
"develop": self._data.get("dev-packages", {}),
}
content = json.dumps(data, sort_keys=True, separators=(",", ":"))
if isinstance(content, six.text_type):
content = content.encode("utf-8")
return Hash.from_hash(hashlib.sha256(content))