♻️ Py3: Remove Py2 specific imports

This commit is contained in:
Gina Häußge committed 2020-10-21 18:13:39 +02:00
1 parent 61a08d26b2
commit 292aa99543
36 files changed
+79 -2375

No files matched your search

+1 -24
View File
@@ -28,30 +28,7 @@ urllib3_ssl = True
a sound SSL environment or not."""
version_info = sys.version_info
if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9:
try:
# make sure our requests version of urllib3 is properly patched (if possible)
import requests.packages.urllib3.contrib.pyopenssl
requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
try:
import urllib3
# only proceed if urllib3 is even installed on its own
try:
# urllib3 is there, let's patch that too
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
except ImportError:
pass
elif version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32":
if version_info.major == 3 and version_info.minor >= 8 and sys.platform == "win32":
# Python 3.8 makes proactor event loop the default on Windows, Tornado doesn't like that
#
# see https://github.com/tornadoweb/tornado/issues/2608
-5
View File
@@ -1035,11 +1035,6 @@ class MethodReplacedByBooleanProperty:
return self._attr != other
def __bool__(self):
# Python 3
return self._attr
def __nonzero__(self):
# Python 2
return self._attr
def __hash__(self):
+3 -8
View File
@@ -2,17 +2,12 @@ __author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__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 collections
import datetime
import logging
import subprocess
try:
import queue
except ImportError:
import Queue as queue
import collections
import queue
import re
import subprocess
import threading
import octoprint.plugin
+2 -7
View File
@@ -3,15 +3,10 @@ __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 logging
try:
import queue
except ImportError:
import Queue as queue
import collections
import logging
import os
import queue
import threading
import time
+2 -8
View File
@@ -8,16 +8,10 @@ import logging
import os
import re
import shutil
from contextlib import contextmanager
from os import scandir, walk
import pylru
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
from contextlib import contextmanager
from emoji import demojize
from past.builtins import basestring
+1 -2
View File
@@ -239,8 +239,7 @@ class LineProcessorStream(io.RawIOBase):
wrapper `input_stream`.
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
line (bytes): The line as read from `self.input_stream` in byte representation
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
+2 -2
View File
@@ -23,7 +23,7 @@ from octoprint.plugin.core import Plugin, PluginInfo, PluginManager # noqa: F40
from octoprint.plugin.types import * # noqa: F401,F403 ## used by multiple other modules
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.settings import settings as s
from octoprint.util import deprecated, to_native_str
from octoprint.util import deprecated
# singleton
_instance = None
@@ -617,7 +617,7 @@ class PluginSettings:
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = to_native_str(item)
_func.__name__ = item
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
+2 -14
View File
@@ -27,29 +27,17 @@ import inspect
import io
import logging
import os
import sys
from collections import OrderedDict, defaultdict, namedtuple
from os import scandir
import pkg_resources
import pkginfo
from past.builtins import unicode
import octoprint.vendor.imp as imp
from octoprint.util import sv, time_this, to_unicode
from octoprint.util.version import get_python_version_string, is_python_compatible
try:
from os import scandir
except ImportError:
from scandir import scandir
if sys.version_info[0] == 2:
# noinspection PyDeprecation
import imp
else:
# deprecated in Python 3.4+ and hence vendored for now
import octoprint.vendor.imp as imp
# noinspection PyDeprecation
def _find_module(name, path=None):
+1 -4
View File
@@ -1982,10 +1982,7 @@ class SlicerPlugin(OctoPrintPlugin):
..versionadded:: 1.3.7
"""
try:
from os import scandir
except ImportError:
from scandir import scandir
from os import scandir
import octoprint.util
@@ -595,12 +595,7 @@ def _strip_tags(text):
>>> _strip_tags("&#62; &#x3E; Foo") # doctest: +ALLOW_UNICODE
'&#62; &#x3E; Foo'
"""
try:
# noinspection PyCompatibility
from html.parser import HTMLParser
except ImportError:
# noinspection PyCompatibility
from HTMLParser import HTMLParser
from html.parser import HTMLParser
class TagStripper(HTMLParser):
def __init__(self, **kw):
+2 -5
View File
@@ -1,6 +1,8 @@
__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"
from os import scandir
import octoprint.plugin
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
@@ -19,11 +21,6 @@ from octoprint.util.version import (
is_octoprint_compatible,
)
try:
from os import scandir
except ImportError:
from scandir import scandir
try:
import zlib # check if zlib is available
except ImportError:
@@ -8,7 +8,6 @@ from flask_babel import gettext
import octoprint.plugin
from octoprint.access import ADMIN_GROUP, USER_GROUP
from octoprint.util import to_native_str
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
@@ -164,7 +163,7 @@ class PrinterProfileSubwizard:
Subwizards = type(
to_native_str("Subwizards"),
"Subwizards",
tuple(
cls
for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
+16 -34
View File
@@ -8,28 +8,21 @@ The SSDP/UPNP implementations has been largely inspired by https://gist.github.c
For a spec see http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0.pdf
"""
# noinspection PyCompatibility
from builtins import range
import flask
from flask_babel import gettext
import octoprint.plugin
import octoprint.util
try:
# python 3
import zeroconf
except ImportError:
# python 2: vendored version with some backported fixes
import octoprint.vendor.zeroconf as zeroconf
import collections
import platform
import socket
import time
# noinspection PyCompatibility
from builtins import range
import flask
import zeroconf
from flask_babel import gettext
import octoprint.plugin
import octoprint.util
def __plugin_load__():
plugin = DiscoveryPlugin()
@@ -187,20 +180,15 @@ class DiscoveryPlugin(
# ZeroConf
def _format_zeroconf_service_type(self, service_type):
service_type = octoprint.util.to_native_str(service_type)
if not service_type.endswith(octoprint.util.to_native_str(".")):
service_type += octoprint.util.to_native_str(".")
if not service_type.endswith(octoprint.util.to_native_str("local.")):
service_type += octoprint.util.to_native_str("local.")
if not service_type.endswith("."):
service_type += "."
if not service_type.endswith("local."):
service_type += "local."
return service_type
def _format_zeroconf_name(self, name, service_type):
service_type = self._format_zeroconf_service_type(service_type)
return (
octoprint.util.to_native_str(name)
+ octoprint.util.to_native_str(".")
+ service_type
)
return name + "." + service_type
def _format_zeroconf_txt(self, record):
result = {}
@@ -686,13 +674,7 @@ class DiscoveryPlugin(
alive message
"""
try:
# noinspection PyCompatibility
from http.server import BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import BaseHTTPRequestHandler
from http.server import BaseHTTPRequestHandler
from io import BytesIO
socket.setdefaulttimeout(timeout)
+1 -5
View File
@@ -3,6 +3,7 @@ __copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms
import io
import os
from os import scandir
import yaml
from flask import jsonify, make_response, request, url_for
@@ -17,11 +18,6 @@ from octoprint.server import NO_CONTENT
from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado
from octoprint.settings import settings
try:
from os import scandir
except ImportError:
from scandir import scandir
class LoggingPlugin(
octoprint.plugin.AssetPlugin,
@@ -13,6 +13,7 @@ import tempfile
import threading
import time
from datetime import datetime
from os import scandir
import filetype
import pkg_resources
@@ -33,7 +34,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.settings import valid_boolean_trues
from octoprint.util import TemporaryDirectory, to_bytes, to_native_str
from octoprint.util import TemporaryDirectory, to_bytes
from octoprint.util.net import download_file
from octoprint.util.pip import LocalPipCaller
from octoprint.util.platform import get_os, is_os_compatible
@@ -44,11 +45,6 @@ from octoprint.util.version import (
is_python_compatible,
)
try:
from os import scandir
except ImportError:
from scandir import scandir
_DATA_FORMAT_VERSION = "v3"
@@ -568,7 +564,7 @@ class PluginManagerPlugin(
if ext in PluginManagerPlugin.ARCHIVE_EXTENSIONS:
return True
kind = filetype.guess(to_native_str(path))
kind = filetype.guess(path)
if kind:
return ".{}".format(kind.extension) in PluginManagerPlugin.ARCHIVE_EXTENSIONS
return False
@@ -6,7 +6,6 @@ import logging
import pkg_resources
import requests
from octoprint.util import to_native_str # noqa: F401
from octoprint.util.version import (
get_comparable_version,
is_prerelease,
@@ -28,13 +27,13 @@ def _filter_out_latest(releases, include_prerelease=False, python_version=None):
>>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
>>> requires_py3 = ">=3.6, <4"
>>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]}
>>> to_native_str(_filter_out_latest(releases, python_version="2.7.9"))
>>> _filter_out_latest(releases, python_version="2.7.9")
'1.3.12'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="2.7.9"))
>>> _filter_out_latest(releases, include_prerelease=True, python_version="2.7.9")
'1.4.0rc1'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="3.6.0"))
>>> _filter_out_latest(releases, include_prerelease=True, python_version="3.6.0")
'2.0.0rc1'
>>> to_native_str(_filter_out_latest(releases, python_version="3.6.0"))
>>> _filter_out_latest(releases, python_version="3.6.0")
"""
releases = [{"version": k, "data": v[0]} for k, v in releases.items()]
+3 -10
View File
@@ -1,23 +1,16 @@
__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"
# noinspection PyCompatibility
import concurrent.futures
import hashlib
import logging
from urllib.parse import urlencode
import requests
from flask_babel import gettext
import octoprint.plugin
try:
# noinspection PyCompatibility
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
# noinspection PyCompatibility
import concurrent.futures
from octoprint.events import Events
from octoprint.util import RepeatedTimer, monotonic_time
from octoprint.util.version import get_octoprint_version_string
@@ -6,15 +6,11 @@ import collections
import io
import math
import os
import queue
import re
import threading
import time
try:
import queue
except ImportError:
import Queue as queue
try:
from os import scandir
except ImportError:
+1 -5
View File
@@ -148,11 +148,7 @@ import copy
import io
import logging
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
from os import scandir
from octoprint.settings import settings
from octoprint.util import dict_contains_keys, dict_merge, dict_sanitize, is_hidden_path
+1 -7
View File
@@ -2338,15 +2338,9 @@ class Server:
loginManager.init_app(app, add_context_processor=False)
def _start_intermediary_server(self):
try:
# noinspection PyCompatibility
from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import socket
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
host = self._host
port = self._port
+1 -6
View File
@@ -7,13 +7,8 @@ import logging
import os
import tarfile
import zipfile
try:
from os import scandir
except ImportError:
from scandir import scandir
from collections import defaultdict
from os import scandir
from flask import jsonify, make_response, request
from flask_babel import Locale
+1 -5
View File
@@ -10,6 +10,7 @@ import logging
import os
import threading
import time
from os import scandir
import flask
import flask.json
@@ -35,11 +36,6 @@ from octoprint.util import DefaultOrderedDict, deprecated
from octoprint.util.json import JsonEncoding
from octoprint.util.net import is_lan_address
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk # noqa: F401
# ~~ monkey patching
+2 -6
View File
@@ -7,6 +7,7 @@ import mimetypes
import os
import re
import sys
from urllib.parse import urlparse
import tornado
import tornado.escape
@@ -23,11 +24,6 @@ from past.builtins import unicode
import octoprint.util
try:
from urllib.parse import urlparse # py3
except ImportError:
from urlparse import urlparse # py2
from . import PY3
@@ -1415,7 +1411,7 @@ class GlobalHeaderTransform(tornado.web.OutputTransform):
removed_headers = []
return type(
octoprint.util.to_native_str(name),
name,
(GlobalHeaderTransform,),
{
"HEADERS": headers,
+1 -4
View File
@@ -68,10 +68,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
self._watched_folder = None
def initial_scan(self, folder):
try:
from os import scandir
except ImportError:
from scandir import scandir
from os import scandir
def _recursive_scandir(path):
"""Recursively yield DirEntry objects for given directory."""
+1 -5
View File
@@ -6,11 +6,7 @@ import gzip
import logging
import os
import re
try:
from urllib import parse as urlparse
except ImportError:
import urlparse
from urllib import parse as urlparse
import webassets.filter.cssrewrite.urlpath as urlpath
from webassets.bundle import Bundle
+1 -5
View File
@@ -27,6 +27,7 @@ import os
import re
import sys
import time
from collections import ChainMap
import yaml
import yaml.parser
@@ -34,11 +35,6 @@ import yaml.parser
# noinspection PyCompatibility
from past.builtins import basestring
try:
from collections import ChainMap
except ImportError:
from chainmap import ChainMap
try:
from collections.abc import KeysView
except ImportError:
+3 -8
View File
@@ -1,24 +1,19 @@
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
import collections
import datetime
import fnmatch
import io
import logging
import os
import queue
import re
import shutil
import sys
import threading
import time
try:
import queue
except ImportError:
import Queue as queue
import collections
import re
import requests
import sarge
+6 -49
View File
@@ -12,6 +12,7 @@ import copy
import io
import logging
import os
import queue
import re
import shutil
import sys
@@ -21,16 +22,13 @@ import time
import traceback
import warnings
from functools import wraps
from glob import escape
from time import monotonic as monotonic_time # noqa: F401
from typing import Union
import frozendict
import past.builtins
try:
import queue
except ImportError:
import Queue as queue
# noinspection PyCompatibility
from past.builtins import basestring, unicode
@@ -93,16 +91,8 @@ def to_unicode(s_or_u, encoding="utf-8", errors="strict"):
return s_or_u
def to_native_str(s_or_u):
# type: (Union[unicode, bytes]) -> str
"""
Make sure ``s_or_u`` is a native 'str' for the current Python version
Will ensure a byte string under Python 2 and a unicode string under Python 3."""
if sys.version_info[0] == 2:
return to_bytes(s_or_u)
else:
return to_unicode(s_or_u)
to_native_str = to_unicode
"""Synonym for to_unicode, deprecated"""
def sortable_value(value, default_value=""):
@@ -1291,40 +1281,7 @@ def is_hidden_path(path):
return False
try:
from glob import escape
glob_escape = escape
except ImportError:
# no glob.escape - we need to implement our own
_glob_escape_check = re.compile("([*?[])")
_glob_escape_check_bytes = re.compile(b"([*?[])")
def glob_escape(pathname):
"""
Ported from Python 3.4
See https://github.com/python/cpython/commit/fd32fffa5ada8b8be8a65bd51b001d989f99a3d3
"""
drive, pathname = os.path.splitdrive(pathname)
if isinstance(pathname, bytes):
pathname = _glob_escape_check_bytes.sub(br"[\1]", pathname)
else:
pathname = _glob_escape_check.sub(r"[\1]", pathname)
return drive + pathname
try:
# py3
from time import monotonic as monotonic_time
except ImportError:
try:
# py2 w/ suitable source for monotonic time
from monotonic import monotonic as monotonic_time
except RuntimeError:
# no source of monotonic time available, nothing left but using time.time *cringe*
monotonic_time = time.time
glob_escape = escape
def thaw_frozendict(obj):
+3 -11
View File
@@ -11,17 +11,12 @@ import contextlib
import copy
import fnmatch
import glob
import logging
import os
import queue
import re
import threading
import time
try:
import queue
except ImportError:
import Queue as queue
import logging
from collections import deque
import serial
@@ -54,10 +49,7 @@ from octoprint.util.platform import get_os, set_close_exec
try:
import winreg
except ImportError:
try:
import _winreg as winreg
except ImportError:
pass
pass
_logger = logging.getLogger(__name__)
+2 -11
View File
@@ -4,6 +4,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import logging
import queue
import re
import time
@@ -12,13 +13,7 @@ from past.builtins import unicode
from octoprint.util.platform import CLOSE_FDS
from . import to_native_str, to_unicode
from .platform import get_os
try:
import queue
except ImportError: # pragma: no cover
import Queue as queue
from . import to_unicode
# These regexes are based on the colorama package
# Author: Jonathan Hartley
@@ -171,10 +166,6 @@ class CommandlineCaller:
self._logger.debug("Calling: {}".format(joined_command))
self.on_log_call(joined_command)
# if we are running under windows, make sure there are no unicode strings in the env
if get_os() == "windows" and "env" in kwargs:
kwargs["env"] = dict((k, to_native_str(v)) for k, v in kwargs["env"].items())
delimiter = kwargs.get("delimiter", b"\n")
try:
kwargs.pop("delimiter")
+1 -5
View File
@@ -3,11 +3,7 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import logging
import os
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk # noqa: F401
from os import walk
from jinja2 import nodes
from jinja2.ext import Extension
+2 -8
View File
@@ -5,7 +5,6 @@ import io
import logging
import os
import socket
import sys
import netaddr
import netifaces
@@ -41,13 +40,8 @@ if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"):
IPPROTO_IPV6 = socket.IPPROTO_IPV6
IPV6_V6ONLY = socket.IPV6_V6ONLY
else:
if sys.platform == "win32":
# Python 2.7 on Windows lacks IPPROTO_IPV6, but supports the socket options just fine, let's redefine it
IPPROTO_IPV6 = 41
IPV6_V6ONLY = 27
else:
# Whatever we are running on here, we don't want to use V6 on here due to lack of dual stack support
HAS_V6 = False
# Whatever we are running on here, we don't want to use V6 on here due to lack of dual stack support
HAS_V6 = False
def is_lan_address(address, additional_private=None):
+2 -6
View File
@@ -13,7 +13,7 @@ import threading
import pkg_resources
import sarge
from octoprint.util import to_native_str, to_unicode
from octoprint.util import to_unicode
from octoprint.util.platform import CLOSE_FDS
from .commandline import CommandlineCaller, clean_ansi
@@ -445,11 +445,7 @@ class PipCaller(CommandlineCaller):
stdout=sarge.Capture(),
stderr=sarge.Capture(),
cwd=testballoon,
env={
to_native_str("TESTBALLOON_OUTPUT"): to_native_str(
testballoon_output_file
)
},
env={"TESTBALLOON_OUTPUT": testballoon_output_file},
)
except Exception:
self._logger.exception(
-2074
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -5,7 +5,6 @@ import ddt
import octoprint.plugin
import octoprint.plugin.core
from octoprint.util import to_native_str
##~~ Helpers for testing mixin type extraction
@@ -424,7 +423,7 @@ class PluginTestCase(unittest.TestCase):
)
@ddt.unpack
def test_mixins_matching_bases(self, bases_to_set, bases_to_check, expected):
Foo = type(to_native_str("Foo"), bases_to_set, {})
Foo = type("Foo", bases_to_set, {})
actual = octoprint.plugin.core.PluginManager.mixins_matching_bases(
Foo, *bases_to_check
)
+4 -5
View File
@@ -11,7 +11,6 @@ from ddt import data, ddt, unpack
import octoprint.plugin
import octoprint.settings
from octoprint.util import to_native_str
@ddt
@@ -145,8 +144,8 @@ class SettingsTestCase(unittest.TestCase):
called_method = getattr(self.settings, forwarded)
# further mock out our mocked function so things work as they should
called_method.__name__ = to_native_str(forwarded)
called_method.__qualname__ = to_native_str(forwarded)
called_method.__name__ = forwarded
called_method.__qualname__ = forwarded
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)
@@ -385,8 +384,8 @@ class SettingsTestCase(unittest.TestCase):
called_method = getattr(self.settings, forwarded)
# further mock out our mocked function so things work as they should
called_method.__name__ = to_native_str(forwarded)
called_method.__qualname__ = to_native_str(forwarded)
called_method.__name__ = forwarded
called_method.__qualname__ = forwarded
called_method.__annotations__ = {}
method = getattr(self.plugin_settings, deprecated)