Merge pull request #3981 from eumiro/py36plus

🚀 Modernize the code to Python 3.6+
This commit is contained in:
Gina Häußge authored and GitHub committed 2021-01-26 10:53:45 +01:00
commit 5e620bcdfe
39 files changed
+93 -111

No files matched your search

+3 -3
View File
@@ -107,7 +107,7 @@ class CodeBlockExt(CodeBlock):
return literal
class PygmentsBridgeExt(object):
class PygmentsBridgeExt:
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
@@ -133,7 +133,7 @@ class PygmentsBridgeExt(object):
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
class whitespace:
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
@@ -229,7 +229,7 @@ class PygmentsBridgeExt(object):
return hlsource
class whitespace_highlighter(object):
class whitespace_highlighter:
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
+2 -2
View File
@@ -87,7 +87,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
@@ -151,7 +151,7 @@ def git_get_keywords(versionfile_abs):
if mo:
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
except OSError:
pass
return keywords
+1 -1
View File
@@ -267,7 +267,7 @@ class PermissionsMetaClass(type):
return None
class Permissions(object, metaclass=PermissionsMetaClass):
class Permissions(metaclass=PermissionsMetaClass):
# Special permission
ADMIN = OctoPrintPermission(
+1 -3
View File
@@ -191,9 +191,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
"plugin_source": source,
"plugin_installurl": installurl,
}
options = dict(
(k, v) for k, v in raw_options.items() if v is not None
)
options = {k: v for k, v in raw_options.items() if v is not None}
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter(
+1 -1
View File
@@ -155,7 +155,7 @@ class Daemon:
try:
with io.open(self.pidfile, "rt", encoding="utf-8") as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
except (OSError, ValueError):
pid = None
return pid
+1 -2
View File
@@ -537,8 +537,7 @@ class LocalFileStorage(StorageInterface):
if path:
path = self.sanitize_path(path)
for entry in self._analysis_backlog_generator(path):
yield entry
yield from self._analysis_backlog_generator(path)
def _analysis_backlog_generator(self, path=None):
if path is None:
+3 -5
View File
@@ -1325,9 +1325,7 @@ class PluginManager:
force_reload = []
added, found = self.find_plugins(
existing=dict(
(k, v) for k, v in self.plugins.items() if k not in force_reload
),
existing={k: v for k, v in self.plugins.items() if k not in force_reload},
incl_all_found=True,
)
@@ -2178,7 +2176,7 @@ class PluginManager:
all_helpers = plugin.helpers
if len(helpers):
return dict((k, v) for (k, v) in all_helpers.items() if k in helpers)
return {k: v for (k, v) in all_helpers.items() if k in helpers}
else:
return all_helpers
@@ -2306,7 +2304,7 @@ class EntryPointMetadata(pkginfo.Distribution):
for metadata_file in metadata_files:
try:
return self.entry_point.dist.get_metadata(metadata_file)
except (IOError, OSError): # noqa: B014
except OSError: # noqa: B014
# file not found, metadata file might be missing, ignore
# IOError: file not found in Py2
# OSError (specifically FileNotFoundError): file not found in Py3
+3 -4
View File
@@ -244,10 +244,9 @@ class AppKeysPlugin(
return flask.jsonify(
keys=list(map(lambda x: x.external(), keys)),
pending=dict(
(x.user_token, x.external())
for x in self._get_pending_by_user_id(user_id)
),
pending={
x.user_token: x.external() for x in self._get_pending_by_user_id(user_id)
},
)
def on_api_command(self, command, data):
+1 -3
View File
@@ -845,9 +845,7 @@ class BackupPlugin(
from octoprint.plugins.pluginmanager import map_repository_entry
return dict(
(plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())
)
return {plugin["id"]: plugin for plugin in map(map_repository_entry, r.json())}
@classmethod
def _install_plugin(
+6 -6
View File
@@ -30,11 +30,11 @@ class CoreWizardPlugin(
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict(
(key, value)
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
}
result = list()
for key, method in required.items():
@@ -82,11 +82,11 @@ class CoreWizardPlugin(
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict(
(key, value)
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
}
any_required = any(map(lambda m: m(), required.values()))
return any_required
+3 -3
View File
@@ -181,11 +181,11 @@ class LoggingPlugin(
if config is None or not isinstance(config, dict):
return {}
return dict(
(key, value.get("level"))
return {
key: value.get("level")
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value
)
}
def _set_logging_levels(self, new_levels):
import logging
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -1612,11 +1612,11 @@ class SoftwareUpdatePlugin(
updater_thread.daemon = False
updater_thread.start()
check_data = dict(
(key, check["displayName"] if "displayName" in check else key)
check_data = {
key: check["displayName"] if "displayName" in check else key
for key, check in populated_checks.items()
if key in to_be_updated
)
}
return to_be_updated, check_data
def _update_worker(self, checks, check_targets, force):
@@ -44,7 +44,7 @@ class CheckError(Exception):
class RateLimitCheckError(CheckError):
def __init__(self, message, remaining=None, limit=None, reset=None):
super(RateLimitCheckError, self).__init__(message)
super().__init__(message)
self.remaining = remaining
self.limit = limit
self.reset = reset
@@ -153,7 +153,7 @@ def _git(args, cwd, git_executable=None):
command = [c] + args
try:
return _execute(command, cwd=cwd)
except EnvironmentError:
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
@@ -24,9 +24,7 @@ class GithubRateLimitCheckError(RateLimitCheckError):
message = "Github rate limit exceeded, reset at {}".format(reset)
else:
message = "Github rate limit exceeded"
super(GithubRateLimitCheckError, self).__init__(
message, remaining=remaining, limit=ratelimit, reset=reset
)
super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset)
def log_github_ratelimit(logger, r):
@@ -30,7 +30,7 @@ def _git(args, cwd, hide_stderr=False):
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
except OSError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
@@ -318,10 +318,10 @@ def get_latest(
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict(
(x["branch"], x.get("commitish", [x["branch"]]))
commitishes = {
x["branch"]: x.get("commitish", [x["branch"]])
for x in prerelease_branches
)
}
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", False)
@@ -663,7 +663,7 @@ class VirtualPrinter:
# noinspection PyUnusedLocal
def _gcode_M114(self, data: str) -> bool:
m114FormatString = self._settings.get(["m114FormatString"])
e = dict((index, value) for index, value in enumerate(self._lastE))
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
+4 -4
View File
@@ -1637,11 +1637,11 @@ class Server:
continue
additional_request_data = kwargs.get("_additional_request_data", {})
kwargs = dict(
(k, v)
kwargs = {
k: v
for k, v in kwargs.items()
if not k.startswith("_") and not k == "plugin"
)
}
kwargs.update(additional_request_data)
try:
@@ -2320,7 +2320,7 @@ class Server:
break
else:
self.send_response(404)
self.wfile.write("Not found".encode("utf-8"))
self.wfile.write(b"Not found")
base_path = os.path.realpath(
os.path.join(os.path.dirname(__file__), "..", "static")
+3 -3
View File
@@ -435,10 +435,10 @@ def _saveSettings(data):
if "folder" in data:
try:
folders = dict(
(FOLDER_MAPPING.get(folder, folder), path)
folders = {
FOLDER_MAPPING.get(folder, folder): path
for folder, path in data["folder"].items()
)
}
future = {}
for folder in FOLDER_TYPES:
future[folder] = s.getBaseFolder(folder)
+3 -5
View File
@@ -201,11 +201,9 @@ def _to_client_specs(specs):
for spec in specs.values():
if "action" not in spec or "source" not in spec:
continue
copied = dict(
(k, v)
for k, v in spec.items()
if k in ("source", "action", "name", "confirm")
)
copied = {
k: v for k, v in spec.items() if k in ("source", "action", "name", "confirm")
}
copied["resource"] = url_for(
".executeSystemCommand",
source=spec["source"],
+3 -3
View File
@@ -208,7 +208,7 @@ def fix_webassets_cache():
try:
hash = make_md5(self.V, key)
except IOError as e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
return None
@@ -216,7 +216,7 @@ def fix_webassets_cache():
filename = os.path.join(self.directory, "%s" % hash)
try:
f = io.open(filename, "rb")
except IOError as e:
except OSError as e:
if e.errno != errno.ENOENT:
error_logger.exception(
"Got an exception while trying to open webasset file {}".format(
@@ -1020,7 +1020,7 @@ class PreemptiveCache:
try:
with io.open(self.cachefile, "rt") as f:
cache_data = yaml.safe_load(f)
except IOError as e:
except OSError as e:
import errno
if e.errno != errno.ENOENT:
+4 -6
View File
@@ -225,9 +225,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport
self._file_suffix = file_suffix
self._path = path
self._suffixes = dict(
(key, key) for key in ("name", "path", "content_type", "size")
)
self._suffixes = {key: key for key in ("name", "path", "content_type", "size")}
for suffix_type, suffix in suffixes.items():
if suffix_type in self._suffixes and suffix is not None:
self._suffixes[suffix_type] = suffix
@@ -528,9 +526,9 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport
if "content_type" in part:
parameters["content_type"] = part["content_type"]
fields = dict(
(self._suffixes[key], value) for (key, value) in parameters.items()
)
fields = {
self._suffixes[key]: value for (key, value) in parameters.items()
}
for n, p in fields.items():
if n is None or p is None:
continue
+9 -9
View File
@@ -1598,9 +1598,9 @@ class Settings:
def _validate_config(self):
# validate uniqueness of folder paths
folder_keys = self.get(["folder"], merged=True).keys()
folders = dict(
(folder_key, self.getBaseFolder(folder_key)) for folder_key in folder_keys
)
folders = {
folder_key: self.getBaseFolder(folder_key) for folder_key in folder_keys
}
if len(folders.values()) != len(set(folders.values())):
raise DuplicateFolderPaths(folders)
@@ -2178,7 +2178,7 @@ def _validate_folder(
if not os.path.exists(folder):
if os.path.islink(folder):
# broken symlink, see #2644
raise IOError("Folder at {} appears to be a broken symlink".format(folder))
raise OSError("Folder at {} appears to be a broken symlink".format(folder))
elif create:
# non existing, but we are allowed to create it
@@ -2187,7 +2187,7 @@ def _validate_folder(
except Exception:
if log_error:
logger.exception("Could not create {}".format(folder))
raise IOError(
raise OSError(
"Folder for type {} at {} does not exist and creation failed".format(
type, folder
)
@@ -2195,11 +2195,11 @@ def _validate_folder(
else:
# not extisting, not allowed to create it
raise IOError("No such folder: {}".format(folder))
raise OSError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
raise OSError("Expected a folder at {} but found a file instead".format(folder))
elif check_writable:
# make sure we can also write into the folder
@@ -2207,7 +2207,7 @@ def _validate_folder(
folder
)
if not os.access(folder, os.W_OK):
raise IOError(error)
raise OSError(error)
elif deep_check_writable:
# try to write a file to the folder - on network shares that might be the only reliable way
@@ -2220,4 +2220,4 @@ def _validate_folder(
except Exception:
if log_error:
logger.exception("Could not write test file to {}".format(folder))
raise IOError(error)
raise OSError(error)
+4 -4
View File
@@ -424,7 +424,7 @@ class SlicingManager:
try:
path = self.get_profile_path(slicer, name, must_exist=True)
except IOError:
except OSError:
return None
return self._load_profile_from_path(
slicer, path, require_configured=require_configured
@@ -532,7 +532,7 @@ class SlicingManager:
if name:
try:
profile = self.load_profile(slicer, name)
except (UnknownProfile, IOError):
except (UnknownProfile, OSError):
# in that case we'll use the default profile
pass
@@ -728,7 +728,7 @@ class SlicingManager:
self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name)
)
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
raise IOError(
raise OSError(
"Path to profile {name} tried to break out of allows sub path".format(
**locals()
)
@@ -782,7 +782,7 @@ class SlicingManager:
if default_profiles and slicer in default_profiles:
try:
return self.load_profile(slicer, default_profiles[slicer])
except (UnknownProfile, IOError):
except (UnknownProfile, OSError):
# in that case we'll use the slicers predefined default profile
pass
+2 -3
View File
@@ -1030,8 +1030,7 @@ class fallback_dict(dict):
def _all(self):
yield self.custom
for d in self.fallbacks:
yield d
yield from self.fallbacks
def dict_filter(dictionary, filter_function):
@@ -1072,7 +1071,7 @@ def dict_filter(dictionary, filter_function):
"""
assert isinstance(dictionary, dict)
assert callable(filter_function)
return dict((k, v) for k, v in dictionary.items() if filter_function(k, v))
return {k: v for k, v in dictionary.items() if filter_function(k, v)}
# Source: http://stackoverflow.com/a/6190500/562769
+3 -3
View File
@@ -324,7 +324,7 @@ class PositionRecord:
def as_dict(self):
attrs = self._standard_attrs | {key for key in dir(self) if self.valid_e(key)}
return dict((attr, getattr(self, attr)) for attr in attrs)
return {attr: getattr(self, attr) for attr in attrs}
class TemperatureRecord:
@@ -3874,7 +3874,7 @@ class MachineCom:
try:
line, pos, lineno = self._currentFile.getNext()
except EnvironmentError:
except OSError:
self._log(
"There was an error reading from the file that's being printed, cancelling the print. Please "
"consult octoprint.log for details on the error."
@@ -5462,7 +5462,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
self._current_tool_callback = current_tool_callback
if not os.path.exists(self._filename) or not os.path.isfile(self._filename):
raise IOError("File %s does not exist" % self._filename)
raise OSError("File %s does not exist" % self._filename)
self._size = os.stat(self._filename).st_size
self._pos = 0
self._read_lines = 0
+2 -2
View File
@@ -25,7 +25,7 @@ class SocketTimeout(BaseException):
pass
class SocketClient(object):
class SocketClient:
def __init__(self, url, use_ssl=False, daemon=True, **kwargs):
self._url = url
self._use_ssl = use_ssl
@@ -219,7 +219,7 @@ class SocketClient(object):
return False
class Client(object):
class Client:
def __init__(self, baseurl, apikey):
self.baseurl = baseurl
self.apikey = apikey
+3 -3
View File
@@ -1,6 +1,6 @@
__author__ = u"Gina Häußge <osd@foosel.net>"
__license__ = u"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = u"Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
__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 glob
import os
+1 -1
View File
@@ -13,7 +13,7 @@ from ddt import data, ddt, unpack
from octoprint.filemanager.storage import LocalFileStorage, StorageError
class FileWrapper(object):
class FileWrapper:
def __init__(self, filename):
self.path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "_files", filename
+1 -1
View File
@@ -17,7 +17,7 @@ OLD_VERSION = "1.0.0"
NEW_VERSION = "2.0.0"
class Foo(object):
class Foo:
def get_latest(self, target, check, full_data=None):
information = {
"local": {"name": OLD_VERSION, "value": OLD_VERSION},
+8 -8
View File
@@ -9,7 +9,7 @@ import octoprint.plugin.core
##~~ Helpers for testing mixin type extraction
class A(object):
class A:
pass
@@ -29,7 +29,7 @@ class A1_1(A_1):
pass
class B(object):
class B:
pass
@@ -37,7 +37,7 @@ class B_1(B):
pass
class C(object):
class C:
pass
@@ -45,7 +45,7 @@ class C_1(C):
pass
class D(object):
class D:
pass
@@ -337,7 +337,7 @@ class PluginTestCase(unittest.TestCase):
@ddt.unpack
def test_has_any_of_hooks(self, hooks_to_test_for, plugin_hooks, expected):
plugin = mock.MagicMock()
plugin.hooks = dict((hook, hook) for hook in plugin_hooks)
plugin.hooks = {hook: hook for hook in plugin_hooks}
actual = octoprint.plugin.core.PluginManager.has_any_of_hooks(
plugin, hooks_to_test_for
@@ -346,9 +346,9 @@ class PluginTestCase(unittest.TestCase):
def test_has_any_of_hooks_varargs(self):
plugin = mock.MagicMock()
plugin.hooks = dict(
(hook, hook) for hook in ["octoprint.some_hook", "octoprint.another_hook"]
)
plugin.hooks = {
hook: hook for hook in ["octoprint.some_hook", "octoprint.another_hook"]
}
result = octoprint.plugin.core.PluginManager.has_any_of_hooks(
plugin, "octoprint.some_hook", "octoprint.some_other_hook"
+1 -1
View File
@@ -312,7 +312,7 @@ class TestSettings(unittest.TestCase):
self.assertGreater(len(data), 1)
test_dict = {"enabled": True, "sendWait": True, "waitInterval": 1.0}
test_data = dict((k, v) for k, v in data.items() if k in test_dict)
test_data = {k: v for k, v in data.items() if k in test_dict}
self.assertEqual(test_dict, test_data)
def test_get_multiple(self):
+1 -1
View File
@@ -116,7 +116,7 @@ class TestSlicingManager(unittest.TestCase):
self.slicer_plugin.get_slicer_default_profile.return_value = default_profile
# mock threading
class MockThread(object):
class MockThread:
def __init__(self):
self.target = None
self.args = None
+1 -1
View File
@@ -103,7 +103,7 @@ class TimelapseTest(unittest.TestCase):
"tmp_00000.jpg",
"tmp_00001.jpg",
]
files = dict((f, None) for f in files)
files = {f: None for f in files}
files["old-0.jpg"] = _stat(st_size=10, st_ctime=0, st_mtime=0)
now = self.now
+2 -2
View File
@@ -110,14 +110,14 @@ class TestCommHelpers(unittest.TestCase):
return m.hexdigest()
# rb'' doesn't exist in Python2
temp_regex = r"T:((\d*\.)\d+)".encode("utf-8")
temp_regex = br"T:((\d*\.)\d+)"
temp_template = b"Temp: {}"
temp2_template = b"Temperature: {}"
temp_key = md5sum(temp_regex)
temp_template_key = md5sum(temp_template)
temp2_template_key = md5sum(temp2_template)
x_regex = r"X:(?P<x>\d+)".encode("utf-8")
x_regex = br"X:(?P<x>\d+)"
x_template = b"X: {x}"
x_key = md5sum(x_regex)
x_template_key = md5sum(x_template)
+1 -1
View File
@@ -9,7 +9,7 @@ import unittest.mock as mock
from octoprint.util import RepeatedTimer
class Countdown(object):
class Countdown:
def __init__(self, start):
self._counter = start
+1 -1
View File
@@ -27,7 +27,7 @@ class StringHelperTest(unittest.TestCase):
self.assertRaises(
UnicodeDecodeError,
octoprint.util.to_unicode,
"äöüß".encode("utf-8"),
"äöüß".encode(),
encoding="ascii",
)