Use C YAML loader when possible
This is a lot faster: before _get_options: .339, .317, .220, .321, .315 after _get_options: .037, .106, .037, .145, .089
This commit is contained in:
1 parent
0bd5544284
commit
f3c0c29f69
20 files changed
+249
-254
No files matched your search
@@ -2,7 +2,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import io
|
||||
import logging as log
|
||||
import os
|
||||
import sys
|
||||
@@ -391,10 +390,9 @@ def init_logging(
|
||||
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
from octoprint.util import yaml
|
||||
|
||||
with io.open(logging_file, "rt", encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
config_from_file = yaml.load_from_file(path=logging_file)
|
||||
|
||||
# we merge that with the default config
|
||||
if config_from_file is not None and isinstance(config_from_file, dict):
|
||||
@@ -742,9 +740,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
import time
|
||||
|
||||
import requests
|
||||
import yaml
|
||||
|
||||
from octoprint.util import bom_aware_open
|
||||
from octoprint.util.version import is_octoprint_compatible, is_python_compatible
|
||||
|
||||
logger = log.getLogger(__name__ + ".startup")
|
||||
@@ -810,8 +806,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
if os.stat(path).st_mtime + ttl < time.time():
|
||||
return None
|
||||
|
||||
with bom_aware_open(path, encoding="utf-8", mode="rt") as f:
|
||||
result = yaml.safe_load(f)
|
||||
from octoprint.util import yaml
|
||||
|
||||
result = yaml.load_from_file(path=path)
|
||||
|
||||
if isinstance(result, list):
|
||||
return result
|
||||
@@ -824,8 +821,9 @@ def get_plugin_blacklist(settings, connectivity_checker=None):
|
||||
|
||||
if cache is not None:
|
||||
try:
|
||||
with bom_aware_open(cache, encoding="utf-8", mode="wt") as f:
|
||||
yaml.safe_dump(result, f)
|
||||
from octoprint.util import yaml
|
||||
|
||||
yaml.save_to_file(result, path=cache)
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"Fetched plugin blacklist but couldn't write it to its cache file: %s",
|
||||
|
||||
@@ -5,18 +5,16 @@ __author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
import yaml
|
||||
from past.builtins import basestring
|
||||
|
||||
from octoprint.access import ADMIN_GROUP, GUEST_GROUP, READONLY_GROUP, USER_GROUP
|
||||
from octoprint.access.permissions import OctoPrintPermission, Permissions
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import atomic_write
|
||||
from octoprint.util import atomic_write, yaml
|
||||
from octoprint.vendor.flask_principal import Need, Permission
|
||||
|
||||
GroupNeed = partial(Need, "group")
|
||||
@@ -232,8 +230,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
def _load(self):
|
||||
if os.path.exists(self._groupfile) and os.path.isfile(self._groupfile):
|
||||
try:
|
||||
with io.open(self._groupfile, "rt", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._groupfile)
|
||||
|
||||
if "groups" not in data:
|
||||
groups = data
|
||||
@@ -349,11 +346,7 @@ class FilebasedGroupManager(GroupManager):
|
||||
with atomic_write(
|
||||
self._groupfile, mode="wt", permissions=0o600, max_permissions=0o666
|
||||
) as f:
|
||||
import yaml
|
||||
|
||||
yaml.safe_dump(
|
||||
data, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
@@ -14,7 +13,6 @@ import uuid
|
||||
from builtins import bytes, range
|
||||
|
||||
import wrapt
|
||||
import yaml
|
||||
from flask_login import AnonymousUserMixin, UserMixin
|
||||
from past.builtins import basestring
|
||||
from werkzeug.local import LocalProxy
|
||||
@@ -24,7 +22,7 @@ from octoprint.access.permissions import OctoPrintPermission, Permissions
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.util import atomic_write, deprecated, generate_api_key
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import monotonic_time, to_bytes
|
||||
from octoprint.util import monotonic_time, to_bytes, yaml
|
||||
|
||||
|
||||
class UserManager(GroupChangeListener, object):
|
||||
@@ -519,64 +517,60 @@ class FilebasedUserManager(UserManager):
|
||||
|
||||
def _load(self):
|
||||
if os.path.exists(self._userfile) and os.path.isfile(self._userfile):
|
||||
# noinspection PyBroadException
|
||||
with io.open(self._userfile, "rt", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._userfile)
|
||||
|
||||
if not data or not isinstance(data, dict):
|
||||
self._logger.fatal(
|
||||
"{} does not contain a valid map of users. Fix "
|
||||
"the file, or remove it, then restart OctoPrint.".format(
|
||||
self._userfile
|
||||
)
|
||||
if not data or not isinstance(data, dict):
|
||||
self._logger.fatal(
|
||||
"{} does not contain a valid map of users. Fix "
|
||||
"the file, or remove it, then restart OctoPrint.".format(
|
||||
self._userfile
|
||||
)
|
||||
raise CorruptUserStorage()
|
||||
)
|
||||
raise CorruptUserStorage()
|
||||
|
||||
for name, attributes in data.items():
|
||||
if not isinstance(attributes, dict):
|
||||
continue
|
||||
for name, attributes in data.items():
|
||||
if not isinstance(attributes, dict):
|
||||
continue
|
||||
|
||||
permissions = []
|
||||
if "permissions" in attributes:
|
||||
permissions = attributes["permissions"]
|
||||
permissions = []
|
||||
if "permissions" in attributes:
|
||||
permissions = attributes["permissions"]
|
||||
|
||||
if "groups" in attributes:
|
||||
groups = set(attributes["groups"])
|
||||
else:
|
||||
groups = {self._group_manager.user_group}
|
||||
if "groups" in attributes:
|
||||
groups = set(attributes["groups"])
|
||||
else:
|
||||
groups = {self._group_manager.user_group}
|
||||
|
||||
# migrate from roles to permissions
|
||||
if "roles" in attributes and "permissions" not in attributes:
|
||||
self._logger.info(
|
||||
"Migrating user {} to new granular permission system".format(
|
||||
name
|
||||
)
|
||||
)
|
||||
|
||||
groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
|
||||
self._dirty = True
|
||||
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = {}
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
self._users[name] = User(
|
||||
username=name,
|
||||
passwordHash=attributes["password"],
|
||||
active=attributes["active"],
|
||||
permissions=self._to_permissions(*permissions),
|
||||
groups=self._to_groups(*groups),
|
||||
apikey=apikey,
|
||||
settings=settings,
|
||||
# migrate from roles to permissions
|
||||
if "roles" in attributes and "permissions" not in attributes:
|
||||
self._logger.info(
|
||||
"Migrating user {} to new granular permission system".format(name)
|
||||
)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(
|
||||
self._users[name]
|
||||
)
|
||||
|
||||
groups |= set(self._migrate_roles_to_groups(attributes["roles"]))
|
||||
self._dirty = True
|
||||
|
||||
apikey = None
|
||||
if "apikey" in attributes:
|
||||
apikey = attributes["apikey"]
|
||||
settings = {}
|
||||
if "settings" in attributes:
|
||||
settings = attributes["settings"]
|
||||
|
||||
self._users[name] = User(
|
||||
username=name,
|
||||
passwordHash=attributes["password"],
|
||||
active=attributes["active"],
|
||||
permissions=self._to_permissions(*permissions),
|
||||
groups=self._to_groups(*groups),
|
||||
apikey=apikey,
|
||||
settings=settings,
|
||||
)
|
||||
for sessionid in self._sessionids_by_userid.get(name, set()):
|
||||
if sessionid in self._session_users_by_session:
|
||||
self._session_users_by_session[sessionid].update_user(
|
||||
self._users[name]
|
||||
)
|
||||
|
||||
if self._dirty:
|
||||
self._save()
|
||||
@@ -608,9 +602,7 @@ class FilebasedUserManager(UserManager):
|
||||
with atomic_write(
|
||||
self._userfile, mode="wt", permissions=0o600, max_permissions=0o666
|
||||
) as f:
|
||||
yaml.safe_dump(
|
||||
data, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
self._dirty = False
|
||||
self._load()
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import sys
|
||||
|
||||
import click
|
||||
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
# ~~ "octoprint util" commands
|
||||
@@ -97,8 +99,6 @@ def gcode_command(
|
||||
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util.gcodeInterpreter import gcode
|
||||
|
||||
@@ -156,14 +156,7 @@ def gcode_command(
|
||||
sys.exit(-1)
|
||||
|
||||
click.echo("RESULTS:")
|
||||
click.echo(
|
||||
yaml.safe_dump(
|
||||
interpreter.get_result(),
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
)
|
||||
click.echo(yaml.dump(interpreter.get_result(), pretty=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -13,6 +13,7 @@ from past.builtins import unicode
|
||||
import octoprint_client
|
||||
from octoprint import FatalStartupError, init_settings
|
||||
from octoprint.cli import bulk_options, get_ctx_obj_option
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -170,10 +171,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
|
||||
with io.open(file_path, "rt") as fp:
|
||||
data = json.load(fp)
|
||||
else:
|
||||
import yaml
|
||||
|
||||
with io.open(file_path, "rt") as fp:
|
||||
data = yaml.safe_load(fp)
|
||||
data = yaml.load_from_file(path=file_path)
|
||||
|
||||
r = ctx.obj.client.post_json(path, data, timeout=timeout)
|
||||
else:
|
||||
|
||||
@@ -10,10 +10,10 @@ import logging
|
||||
import pprint
|
||||
|
||||
import click
|
||||
import yaml
|
||||
|
||||
from octoprint import FatalStartupError, init_settings
|
||||
from octoprint.cli import get_ctx_obj_option, standard_options
|
||||
from octoprint.util import yaml
|
||||
|
||||
click.disable_unicode_literals_warning = True
|
||||
|
||||
@@ -217,9 +217,7 @@ def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(
|
||||
value, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
output = yaml.dump(value, pretty=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
@@ -243,9 +241,7 @@ def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
|
||||
if as_json:
|
||||
output = json.dumps(value)
|
||||
elif as_yaml:
|
||||
output = yaml.safe_dump(
|
||||
value, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
output = yaml.dump(value, pretty=True)
|
||||
elif as_raw:
|
||||
output = value
|
||||
else:
|
||||
|
||||
@@ -11,9 +11,9 @@ import sys
|
||||
import threading
|
||||
|
||||
import psutil
|
||||
import yaml
|
||||
|
||||
from octoprint.plugin import EnvironmentDetectionPlugin
|
||||
from octoprint.util import yaml
|
||||
from octoprint.util.platform import get_os
|
||||
from octoprint.util.version import get_python_version_string
|
||||
|
||||
@@ -168,9 +168,7 @@ class EnvironmentDetector(object):
|
||||
self.run_detection()
|
||||
environment = copy.deepcopy(self._cache)
|
||||
|
||||
dumped_environment = yaml.safe_dump(
|
||||
environment, default_flow_style=False, indent=2, allow_unicode=True
|
||||
).strip()
|
||||
dumped_environment = yaml.dump(environment, pretty=True).strip()
|
||||
environment_lines = "\n".join(
|
||||
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
|
||||
)
|
||||
|
||||
@@ -5,7 +5,6 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
from collections import namedtuple
|
||||
@@ -16,6 +15,7 @@ import octoprint.plugin
|
||||
import octoprint.util
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import yaml
|
||||
|
||||
from .analysis import AnalysisQueue, QueueEntry # noqa: F401
|
||||
from .destinations import FileDestinations # noqa: F401
|
||||
@@ -941,8 +941,6 @@ class FileManager(object):
|
||||
def save_recovery_data(self, origin, path, pos):
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
data = {
|
||||
@@ -953,9 +951,7 @@ class FileManager(object):
|
||||
}
|
||||
try:
|
||||
with atomic_write(self._recovery_file, mode="wt", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(
|
||||
data, stream=f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(data, file=f, pretty=True)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not write recovery data to file {}".format(self._recovery_file)
|
||||
@@ -976,11 +972,9 @@ class FileManager(object):
|
||||
if not os.path.isfile(self._recovery_file):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(self._recovery_file, "rt", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._recovery_file)
|
||||
|
||||
if not isinstance(data, dict) or not all(
|
||||
map(lambda x: x in data, ("origin", "path", "pos", "date"))
|
||||
):
|
||||
|
||||
@@ -22,7 +22,7 @@ from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_merge
|
||||
from octoprint.util import get_fully_qualified_classname as fqcn
|
||||
from octoprint.util import monotonic_time
|
||||
from octoprint.util import monotonic_time, yaml
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
|
||||
EMPTY_RESULT = {
|
||||
@@ -414,7 +414,6 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
import sys
|
||||
|
||||
import sarge
|
||||
import yaml
|
||||
|
||||
if self._current.analysis and all(
|
||||
map(
|
||||
@@ -508,7 +507,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
|
||||
raise RuntimeError("No analysis result found")
|
||||
else:
|
||||
_, output = output.split("RESULTS:")
|
||||
analysis = yaml.safe_load(output)
|
||||
analysis = yaml.load_from_file(file=output)
|
||||
|
||||
result["printingArea"] = analysis["printing_area"]
|
||||
result["dimensions"] = analysis["dimensions"]
|
||||
|
||||
@@ -23,7 +23,14 @@ from contextlib import contextmanager
|
||||
from past.builtins import basestring
|
||||
|
||||
import octoprint.filemanager
|
||||
from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode
|
||||
from octoprint.util import (
|
||||
atomic_write,
|
||||
is_hidden_path,
|
||||
time_this,
|
||||
to_bytes,
|
||||
to_unicode,
|
||||
yaml,
|
||||
)
|
||||
from octoprint.util.files import sanitize_filename
|
||||
|
||||
|
||||
@@ -515,10 +522,7 @@ class LocalFileStorage(StorageInterface):
|
||||
if os.path.exists(old_metadata_path):
|
||||
# load the old metadata file
|
||||
try:
|
||||
with io.open(old_metadata_path, "rt", encoding="utf-8") as f:
|
||||
import yaml
|
||||
|
||||
self._old_metadata = yaml.safe_load(f)
|
||||
self._old_metadata = yaml.load_from_file(path=old_metadata_path)
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading old metadata file")
|
||||
|
||||
@@ -1903,8 +1907,6 @@ class LocalFileStorage(StorageInterface):
|
||||
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
|
||||
import json
|
||||
|
||||
import yaml
|
||||
|
||||
with self._get_persisted_metadata_lock(path):
|
||||
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
|
||||
metadata_path_json = os.path.join(path, ".metadata.json")
|
||||
@@ -1925,16 +1927,13 @@ class LocalFileStorage(StorageInterface):
|
||||
)
|
||||
return
|
||||
|
||||
with io.open(metadata_path_yaml, "rt", encoding="utf-8") as f:
|
||||
try:
|
||||
metadata = yaml.safe_load(f)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while reading .metadata.yaml from {path}".format(
|
||||
**locals()
|
||||
)
|
||||
)
|
||||
return
|
||||
try:
|
||||
metadata = yaml.load_from_file(path=metadata_path_yaml)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Error while reading .metadata.yaml from {path}".format(**locals())
|
||||
)
|
||||
return
|
||||
|
||||
if not isinstance(metadata, dict):
|
||||
# looks invalid, ignore it
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
import io
|
||||
import os
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
|
||||
import flask
|
||||
import yaml
|
||||
from flask_babel import gettext
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -16,7 +14,13 @@ from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT, admin_permission, current_user
|
||||
from octoprint.server.util.flask import no_firstrun_access, restricted_access
|
||||
from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.util import ResettableTimer, atomic_write, generate_api_key, monotonic_time
|
||||
from octoprint.util import (
|
||||
ResettableTimer,
|
||||
atomic_write,
|
||||
generate_api_key,
|
||||
monotonic_time,
|
||||
yaml,
|
||||
)
|
||||
|
||||
CUTOFF_TIME = 10 * 60 # 10min
|
||||
POLL_TIMEOUT = 5 # 5 seconds
|
||||
@@ -441,10 +445,7 @@ class AppKeysPlugin(
|
||||
return
|
||||
|
||||
try:
|
||||
with io.open(
|
||||
self._key_path, "rt", encoding="utf-8", errors="strict"
|
||||
) as f:
|
||||
persisted = yaml.safe_load(f)
|
||||
persisted = yaml.load_from_file(path=self._key_path)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not load application keys from {}".format(self._key_path)
|
||||
@@ -469,7 +470,7 @@ class AppKeysPlugin(
|
||||
|
||||
try:
|
||||
with atomic_write(self._key_path, mode="wt") as f:
|
||||
yaml.safe_dump(to_persist, f, allow_unicode=True)
|
||||
yaml.save_to_file(to_persist, file=f)
|
||||
except Exception:
|
||||
self._logger.exception(
|
||||
"Could not write application keys to {}".format(self._key_path)
|
||||
|
||||
@@ -11,7 +11,7 @@ from octoprint.events import Events
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access
|
||||
from octoprint.settings import default_settings
|
||||
from octoprint.util import is_hidden_path, to_bytes
|
||||
from octoprint.util import is_hidden_path, to_bytes, yaml
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.platform import is_os_compatible
|
||||
from octoprint.util.version import (
|
||||
@@ -1197,10 +1197,7 @@ class BackupPlugin(
|
||||
on_restore_failed(path)
|
||||
return False
|
||||
|
||||
import yaml
|
||||
|
||||
with io.open(configfile, "rt", encoding="utf-8") as f:
|
||||
configdata = yaml.safe_load(f)
|
||||
configdata = yaml.load_from_file(path=configfile)
|
||||
|
||||
userfile = os.path.join(temp, "basedir", "users.yaml")
|
||||
if not os.path.exists(userfile):
|
||||
|
||||
@@ -4,10 +4,8 @@ from __future__ import absolute_import, division, print_function, unicode_litera
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
import yaml
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
from werkzeug.exceptions import BadRequest
|
||||
@@ -19,7 +17,7 @@ from octoprint.access.permissions import Permissions
|
||||
from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import is_hidden_path
|
||||
from octoprint.util import is_hidden_path, yaml
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
@@ -188,10 +186,7 @@ class LoggingPlugin(
|
||||
|
||||
config_from_file = {}
|
||||
if os.path.exists(logging_file) and os.path.isfile(logging_file):
|
||||
import yaml
|
||||
|
||||
with io.open(logging_file, "rt", encoding="utf-8") as f:
|
||||
config_from_file = yaml.safe_load(f)
|
||||
config_from_file = yaml.load_from_file(path=logging_file)
|
||||
return config_from_file
|
||||
|
||||
def _get_logging_levels(self):
|
||||
@@ -241,9 +236,7 @@ class LoggingPlugin(
|
||||
with octoprint.util.atomic_write(
|
||||
self._get_logging_file(), mode="wt", max_permissions=0o666
|
||||
) as f:
|
||||
yaml.safe_dump(
|
||||
config, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(config, file=f, pretty=True)
|
||||
|
||||
# set runtime logging levels now
|
||||
for logger, level in new_levels.items():
|
||||
|
||||
@@ -10,7 +10,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
@@ -34,7 +33,7 @@ from octoprint.server.util.flask import (
|
||||
no_firstrun_access,
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.util import dict_merge, get_formatted_size, to_unicode
|
||||
from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.version import (
|
||||
get_comparable_version,
|
||||
@@ -476,11 +475,8 @@ class SoftwareUpdatePlugin(
|
||||
if not os.path.isfile(self._version_cache_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(self._version_cache_path, "rt", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._version_cache_path)
|
||||
timestamp = os.stat(self._version_cache_path).st_mtime
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading version cache from disk")
|
||||
@@ -517,8 +513,6 @@ class SoftwareUpdatePlugin(
|
||||
self._logger.exception("Error parsing in version cache data")
|
||||
|
||||
def _save_version_cache(self):
|
||||
import yaml
|
||||
|
||||
from octoprint._version import get_versions
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
@@ -528,13 +522,7 @@ class SoftwareUpdatePlugin(
|
||||
with atomic_write(
|
||||
self._version_cache_path, mode="wt", max_permissions=0o666
|
||||
) as file_obj:
|
||||
yaml.safe_dump(
|
||||
self._version_cache,
|
||||
stream=file_obj,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(self._version_cache, file=file_obj, pretty=True)
|
||||
|
||||
self._version_cache_dirty = False
|
||||
self._version_cache_timestamp = time.time()
|
||||
@@ -552,11 +540,8 @@ class SoftwareUpdatePlugin(
|
||||
if not os.path.isfile(self._update_log_path):
|
||||
return
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(self._update_log_path, "rt", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f)
|
||||
data = yaml.load_from_file(path=self._update_log_path)
|
||||
except Exception:
|
||||
self._logger.exception("Error while loading update log from disk")
|
||||
else:
|
||||
@@ -588,20 +573,16 @@ class SoftwareUpdatePlugin(
|
||||
self._logger.info("Loaded update log from disk")
|
||||
|
||||
def _save_update_log(self):
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
with self._update_log_mutex:
|
||||
with atomic_write(
|
||||
self._update_log_path, mode="wt", max_permissions=0o666
|
||||
) as file_obj:
|
||||
yaml.safe_dump(
|
||||
yaml.save_to_file(
|
||||
sorted(self._update_log, key=lambda x: x["datetime"]),
|
||||
stream=file_obj,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
file=file_obj,
|
||||
pretty=True,
|
||||
)
|
||||
self._update_log_dirty = False
|
||||
|
||||
|
||||
@@ -147,7 +147,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
|
||||
@@ -157,7 +156,13 @@ except ImportError:
|
||||
from scandir import scandir
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path
|
||||
from octoprint.util import (
|
||||
dict_contains_keys,
|
||||
dict_merge,
|
||||
dict_sanitize,
|
||||
is_hidden_path,
|
||||
yaml,
|
||||
)
|
||||
|
||||
|
||||
class SaveError(Exception):
|
||||
@@ -507,10 +512,7 @@ class PrinterProfileManager(object):
|
||||
if not os.path.exists(path) or not os.path.isfile(path):
|
||||
return None
|
||||
|
||||
import yaml
|
||||
|
||||
with io.open(path, "rt", encoding="utf-8") as f:
|
||||
profile = yaml.safe_load(f)
|
||||
profile = yaml.load_from_file(path=path)
|
||||
|
||||
if profile is None or not isinstance(profile, dict):
|
||||
raise InvalidProfileError("Profile is None or not a dictionary")
|
||||
@@ -542,15 +544,11 @@ class PrinterProfileManager(object):
|
||||
"Profile %s already exists and not allowed to overwrite" % profile["id"]
|
||||
)
|
||||
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
try:
|
||||
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
|
||||
yaml.safe_dump(
|
||||
profile, f, default_flow_style=False, indent=2, allow_unicode=True
|
||||
)
|
||||
yaml.save_to_file(profile, file=f, pretty=True)
|
||||
except Exception as e:
|
||||
self._logger.exception(
|
||||
"Error while trying to save profile %s" % profile["id"]
|
||||
|
||||
@@ -5,12 +5,13 @@ __author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
from octoprint.util import yaml
|
||||
|
||||
try:
|
||||
from os import scandir
|
||||
except ImportError:
|
||||
@@ -49,11 +50,8 @@ def getInstalledLanguagePacks():
|
||||
|
||||
meta_path = os.path.join(path, "meta.yaml")
|
||||
if os.path.isfile(meta_path):
|
||||
import yaml
|
||||
|
||||
try:
|
||||
with io.open(meta_path, "rt", encoding="utf-8") as f:
|
||||
meta = yaml.safe_load(f)
|
||||
meta = yaml.load_from_file(path=meta_path)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Could not load %s", meta_path)
|
||||
pass
|
||||
|
||||
@@ -34,7 +34,7 @@ import octoprint.server
|
||||
import octoprint.vendor.flask_principal as flask_principal
|
||||
from octoprint.events import Events, eventManager
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util import DefaultOrderedDict, deprecated
|
||||
from octoprint.util import DefaultOrderedDict, deprecated, yaml
|
||||
from octoprint.util.json import JsonEncoding
|
||||
from octoprint.util.net import is_lan_address
|
||||
|
||||
@@ -1023,13 +1023,10 @@ class PreemptiveCache(object):
|
||||
return all_data
|
||||
|
||||
def get_all_data(self):
|
||||
import yaml
|
||||
|
||||
cache_data = None
|
||||
with self._lock:
|
||||
try:
|
||||
with io.open(self.cachefile, "rt") as f:
|
||||
cache_data = yaml.safe_load(f)
|
||||
cache_data = yaml.load_from_file(path=self.cachefile)
|
||||
except IOError as e:
|
||||
import errno
|
||||
|
||||
@@ -1052,20 +1049,12 @@ class PreemptiveCache(object):
|
||||
return cache_data.get(root, list())
|
||||
|
||||
def set_all_data(self, data):
|
||||
import yaml
|
||||
|
||||
from octoprint.util import atomic_write
|
||||
|
||||
with self._lock:
|
||||
try:
|
||||
with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle:
|
||||
yaml.safe_dump(
|
||||
data,
|
||||
handle,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(data, file=handle, pretty=True)
|
||||
except Exception:
|
||||
self._logger.exception("Error while writing {}".format(self.cachefile))
|
||||
|
||||
|
||||
+10
-22
@@ -31,11 +31,9 @@ import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import yaml
|
||||
import yaml.parser
|
||||
|
||||
# noinspection PyCompatibility
|
||||
# noinspection PyCompatibilitys
|
||||
from past.builtins import basestring
|
||||
from yaml import YAMLError
|
||||
|
||||
try:
|
||||
from collections import ChainMap
|
||||
@@ -58,6 +56,7 @@ from octoprint.util import (
|
||||
dict_merge,
|
||||
generate_api_key,
|
||||
is_hidden_path,
|
||||
yaml,
|
||||
)
|
||||
|
||||
_APPNAME = "OctoPrint"
|
||||
@@ -956,9 +955,7 @@ class Settings(object):
|
||||
|
||||
@property
|
||||
def effective_yaml(self):
|
||||
import yaml
|
||||
|
||||
return yaml.safe_dump(self.effective)
|
||||
return yaml.dump(self.effective)
|
||||
|
||||
@property
|
||||
def effective_hash(self):
|
||||
@@ -974,9 +971,7 @@ class Settings(object):
|
||||
|
||||
@property
|
||||
def config_yaml(self):
|
||||
import yaml
|
||||
|
||||
return yaml.safe_dump(self._config)
|
||||
return yaml.dump(self._config)
|
||||
|
||||
@property
|
||||
def config_hash(self):
|
||||
@@ -1028,10 +1023,10 @@ class Settings(object):
|
||||
if os.path.exists(self._configfile) and os.path.isfile(self._configfile):
|
||||
with io.open(self._configfile, "rt", encoding="utf-8", errors="replace") as f:
|
||||
try:
|
||||
self._config = yaml.safe_load(f)
|
||||
self._config = yaml.load_from_file(file=f)
|
||||
self._mtime = self.last_modified
|
||||
|
||||
except yaml.YAMLError as e:
|
||||
except YAMLError as e:
|
||||
details = str(e)
|
||||
|
||||
if hasattr(e, "problem_mark"):
|
||||
@@ -1097,8 +1092,7 @@ class Settings(object):
|
||||
|
||||
if isinstance(overlay, basestring):
|
||||
if os.path.exists(overlay) and os.path.isfile(overlay):
|
||||
with io.open(overlay, "rt", encoding="utf-8", errors="replace") as f:
|
||||
config = yaml.safe_load(f)
|
||||
config = yaml.load_from_file(path=overlay)
|
||||
elif isinstance(overlay, dict):
|
||||
config = overlay
|
||||
else:
|
||||
@@ -1119,7 +1113,7 @@ class Settings(object):
|
||||
assert isinstance(overlay, dict)
|
||||
|
||||
if key is None:
|
||||
overlay_yaml = yaml.safe_dump(overlay)
|
||||
overlay_yaml = yaml.dump(overlay)
|
||||
import hashlib
|
||||
|
||||
hash = hashlib.md5()
|
||||
@@ -1688,13 +1682,7 @@ class Settings(object):
|
||||
permissions=0o600,
|
||||
max_permissions=0o666,
|
||||
) as configFile:
|
||||
yaml.safe_dump(
|
||||
self._config,
|
||||
configFile,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
)
|
||||
yaml.save_to_file(self._config, file=configFile)
|
||||
self._dirty = False
|
||||
except Exception:
|
||||
self._logger.exception("Error while saving config.yaml!")
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
|
||||
from octoprint.util import bom_aware_open
|
||||
|
||||
|
||||
def load_from_file(file=None, path=None):
|
||||
"""
|
||||
Safely and performantly loads yaml data from the given source. Either a
|
||||
path or a file must be passed in.
|
||||
|
||||
:rtype: Union[dict[Hashable, Any], list, None]
|
||||
:type path: str | None
|
||||
:type file: typing.TextIO | None
|
||||
"""
|
||||
if path is not None:
|
||||
assert file is None
|
||||
with bom_aware_open(path, mode="rt", encoding="utf-8") as f:
|
||||
return load_from_file(file=f)
|
||||
|
||||
if file is not None:
|
||||
assert path is None
|
||||
|
||||
assert path is not None or file is not None, "this function requires an input file"
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
from yaml import CSafeLoader as SafeLoader
|
||||
except ImportError:
|
||||
from yaml import SafeLoader
|
||||
|
||||
return yaml.load(file, Loader=SafeLoader)
|
||||
|
||||
|
||||
def _save_to_file_base(data, file=None, path=None, pretty=False, **kwargs):
|
||||
if path is not None:
|
||||
assert file is None
|
||||
with io.open(path, "wt", encoding="utf-8") as f:
|
||||
return _save_to_file_base(data, file=f, pretty=pretty, **kwargs)
|
||||
|
||||
if file is not None:
|
||||
assert path is None
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
from yaml import CSafeDumper as SafeDumper
|
||||
except ImportError:
|
||||
from yaml import SafeDumper
|
||||
|
||||
if pretty:
|
||||
# make each element go on a new line and indent by 2
|
||||
kwargs.update(default_flow_style=False, indent=2)
|
||||
|
||||
return yaml.dump(
|
||||
data,
|
||||
stream=file,
|
||||
Dumper=SafeDumper,
|
||||
allow_unicode=True, # no good reason not to allow it these days
|
||||
**kwargs
|
||||
)
|
||||
|
||||
|
||||
def save_to_file(data, file=None, path=None, pretty=False, **kwargs):
|
||||
"""
|
||||
Safely and performantly dumps the `data` to yaml.
|
||||
|
||||
To dump to a string, use `yaml.dump()`.
|
||||
|
||||
:type data: object
|
||||
:param data: the data to be serialized
|
||||
:type file: typing.TextIO | None
|
||||
:type path: str | None
|
||||
:type pretty: bool
|
||||
:param pretty: formats the output yaml into a more human-friendly format
|
||||
"""
|
||||
assert file is not None or path is not None, "this function requires an output file"
|
||||
_save_to_file_base(data, file=file, path=path, pretty=pretty, **kwargs)
|
||||
|
||||
|
||||
def dump(data, pretty=False, **kwargs):
|
||||
"""
|
||||
Safely and performantly dumps the `data` to a yaml string.
|
||||
|
||||
:param data: the data to be serialized
|
||||
:param pretty: formats the output yaml into a more human-friendly format
|
||||
:param kwargs: any other args to be passed to the internal yaml.dump() call.
|
||||
:return: yaml-serialized data
|
||||
:rtype: str
|
||||
"""
|
||||
return _save_to_file_base(data, file=None, pretty=pretty, **kwargs)
|
||||
@@ -382,9 +382,11 @@ class FileManagerTest(unittest.TestCase):
|
||||
)
|
||||
|
||||
@mock.patch("octoprint.util.atomic_write", create=True)
|
||||
@mock.patch("yaml.safe_dump", create=True)
|
||||
@mock.patch("octoprint.util.yaml.save_to_file", create=True)
|
||||
@mock.patch("time.time")
|
||||
def test_save_recovery_data(self, mock_time, mock_yaml_safe_dump, mock_atomic_write):
|
||||
def test_save_recovery_data(
|
||||
self, mock_time, mock_yaml_save_to_file, mock_atomic_write
|
||||
):
|
||||
import os
|
||||
|
||||
now = 123456789
|
||||
@@ -411,16 +413,14 @@ class FileManagerTest(unittest.TestCase):
|
||||
"date": now,
|
||||
}
|
||||
|
||||
mock_yaml_safe_dump.assert_called_with(
|
||||
mock_yaml_save_to_file.assert_called_with(
|
||||
expected,
|
||||
stream=mock_atomic_write_handle,
|
||||
default_flow_style=False,
|
||||
indent=2,
|
||||
allow_unicode=True,
|
||||
file=mock_atomic_write_handle,
|
||||
pretty=True,
|
||||
)
|
||||
|
||||
@mock.patch("octoprint.util.atomic_write", create=True)
|
||||
@mock.patch("yaml.safe_dump", create=True)
|
||||
@mock.patch("octoprint.util.yaml.save_to_file", create=True)
|
||||
@mock.patch("time.time")
|
||||
def test_save_recovery_data_with_error(
|
||||
self, mock_time, mock_yaml_safe_dump, mock_atomic_write
|
||||
@@ -471,8 +471,6 @@ class FileManagerTest(unittest.TestCase):
|
||||
def test_get_recovery_data(self, mock_isfile):
|
||||
import os
|
||||
|
||||
import yaml
|
||||
|
||||
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
|
||||
|
||||
data = {
|
||||
@@ -481,16 +479,14 @@ class FileManagerTest(unittest.TestCase):
|
||||
"pos": 1234,
|
||||
"date": 123456789,
|
||||
}
|
||||
text_data = yaml.dump(data)
|
||||
|
||||
with mock.patch(_fixups.OPEN_SIGNATURE, mock.mock_open(read_data=text_data)) as m:
|
||||
# moved safe_load to here so we could mock up the return value properly
|
||||
with mock.patch("yaml.safe_load", return_value=data) as n:
|
||||
result = self.file_manager.get_recovery_data()
|
||||
# moved safe_load to here so we could mock up the return value properly
|
||||
with mock.patch("octoprint.util.yaml.load_from_file", return_value=data) as n:
|
||||
result = self.file_manager.get_recovery_data()
|
||||
|
||||
self.assertDictEqual(data, result)
|
||||
n.assert_called_with(m())
|
||||
mock_isfile.assert_called_with(recovery_file)
|
||||
self.assertDictEqual(data, result)
|
||||
n.assert_called_with(path=recovery_file)
|
||||
mock_isfile.assert_called_with(recovery_file)
|
||||
|
||||
@mock.patch("os.path.isfile")
|
||||
def test_get_recovery_data_no_file(self, mock_isfile):
|
||||
@@ -501,17 +497,17 @@ class FileManagerTest(unittest.TestCase):
|
||||
self.assertIsNone(result)
|
||||
|
||||
@mock.patch("os.path.isfile")
|
||||
@mock.patch("yaml.safe_load")
|
||||
@mock.patch("octoprint.util.yaml.load_from_file")
|
||||
@mock.patch("os.remove")
|
||||
def test_get_recovery_data_broken_file(
|
||||
self, mock_remove, mock_yaml_safe_load, mock_isfile
|
||||
self, mock_remove, mock_yaml_load, mock_isfile
|
||||
):
|
||||
import os
|
||||
|
||||
recovery_file = os.path.join("/path/to/a/base_folder", "print_recovery_data.yaml")
|
||||
|
||||
mock_isfile.return_value = True
|
||||
mock_yaml_safe_load.side_effect = RuntimeError
|
||||
mock_yaml_load.side_effect = RuntimeError
|
||||
|
||||
result = self.file_manager.get_recovery_data()
|
||||
|
||||
|
||||
Reference in new issue
Block a user