diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 8a848511c..37e64bc49 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -14,7 +14,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["2.7", "3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10"] branch: ["master"] runs-on: ${{ matrix.os }} steps: @@ -49,7 +49,7 @@ jobs: strategy: matrix: os: ["ubuntu-latest"] - python: ["2.7", "3.7", "3.8", "3.9", "3.10"] + python: ["3.7", "3.8", "3.9", "3.10"] runs-on: ${{ matrix.os }} steps: - name: 👀 Determine latest release diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 26e4d5b16..589d4bb72 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,15 +11,49 @@ repos: - id: check-toml - id: check-merge-conflict - id: fix-encoding-pragma + args: ["--remove"] + exclude: "setup.py|src/octoprint_setuptools/__init__.py" - repo: https://github.com/asottile/pyupgrade rev: v2.10.0 hooks: - id: pyupgrade + args: ["--py37-plus"] + exclude: "setup.py|src/octoprint_setuptools/__init__.py" - repo: https://github.com/OctoPrint/codemods rev: devel hooks: - id: codemod_not_in args: ["--ignore", "src/octoprint/vendor"] + - id: codemod_detect_past_builtins_imports + args: + [ + "--ignore", + "src/octoprint/vendor", + "--ignore", + "setup.py", + "--ignore", + "src/octoprint_setuptools/__init__.py", + ] + - id: codemod_remove_float_conversion + args: + [ + "--ignore", + "src/octoprint/vendor", + "--ignore", + "setup.py", + "--ignore", + "src/octoprint_setuptools/__init__.py", + ] + - id: codemod_remove_future_imports + args: + [ + "--ignore", + "src/octoprint/vendor", + "--ignore", + "setup.py", + "--ignore", + "src/octoprint_setuptools/__init__.py", + ] - repo: https://github.com/pre-commit/mirrors-isort rev: v5.5.4 hooks: diff --git a/README.md b/README.md index 4a9cf54a3..c68b677fc 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ which is a custom SD card image that includes OctoPrint plus dependencies. The generic steps that should basically be done regardless of operating system and runtime environment are the following (as *regular user*, please keep your hands *off* of the `sudo` command here!) - this assumes -you already have Python 2.7, 3.6 or 3.7, pip and virtualenv and their dependencies set up on your system: +you already have Python 3.7+, pip and virtualenv and their dependencies set up on your system: 1. Create a user-owned virtual environment therein: `virtualenv venv`. If you want to specify a specific python to use instead of whatever version your system defaults to, you can also explicitly require that via the `--python` @@ -87,7 +87,7 @@ access control as necessary. OctoPrint depends on a few python modules to do its job. Those are automatically installed when installing OctoPrint via `pip`. -OctoPrint currently supports Python 2.7, 3.6 and 3.7. +OctoPrint currently supports Python 3.7, 3.8, 3.9 and 3.10. ## Usage diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index 24be587e1..6dd70358c 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -120,9 +120,6 @@ octoprint.plugin.backup.additional_excludes .. code-block:: python - # -*- coding: utf-8 -*- - from __future__ import absolute_import, division, print_function, unicode_literals - import octoprint.plugin import os @@ -150,9 +147,6 @@ octoprint.plugin.backup.additional_excludes .. code-block:: python - # -*- coding: utf-8 -*- - from __future__ import absolute_import, division, print_function, unicode_literals - import octoprint.plugin import os diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index bb675ff86..78cf9de0c 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -635,9 +635,6 @@ octoprint.plugin.softwareupdate.check_config .. code-block:: python - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - def get_update_information(*args, **kwargs): return dict( updateplugindemo=dict( diff --git a/docs/development/environment.rst b/docs/development/environment.rst index b8d989ae3..1176f4df3 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -14,7 +14,7 @@ below. * Prerequisites: - * `Python 3.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` + * `Latest stable Python 3 `_ including ``pip``, ``setuptools`` and ``virtualenv`` * `Git `_ * Checkout the OctoPrint sources from their Git repository: @@ -24,15 +24,15 @@ below. * Enter the checked out source folder: ``cd OctoPrint`` * Create a virtual environment in the checked out source folder to use for installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning - issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv3`` + issues for the dependencies with system wide installed instances: ``virtualenv --python=python3 venv`` .. note:: This assumes that the ``python3`` binary is available directly on your ``PATH``. If it cannot be found on your ``PATH`` like this you'll need to specify the full path here, - e.g. ``virtualenv --python=/path/to/python3/bin/python venv3`` + e.g. ``virtualenv --python=/path/to/python3/bin/python venv`` - * Activate the virtual environment: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) + * Activate the virtual environment: ``source venv/bin/activate`` (Linux, macOS) or ``source venv/Scripts/activate`` (Git Bash under Windows, see below) * Update ``pip`` in the virtual environment: @@ -61,31 +61,6 @@ When the virtual environment is activated you can then: folder -- the documentation will be available in the newly created ``_build`` directory. You can simply browse it locally by opening ``index.html`` -If a Python 2 environment is also desired (e.g. for maintenance reasons), also do the following extra steps: - - * Prerequisites: - - * `Python 2.7 `_ including ``pip``, ``setuptools`` and ``virtualenv`` - - * Create a virtual environment in the checked out source folder for Python 2: ``virtualenv --python=python2 venv2`` - - .. note:: - - This assumes that the ``python2`` binary is available directly on your ``PATH``. If - it cannot be found on your ``PATH`` like this you'll need to specify the full path here, - e.g. ``virtualenv --python=/path/to/python2/bin/python venv2`` - - * Activate the virtual environment: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below) - - * Update ``pip`` in the virtual environment: - - * ``pip install --upgrade pip`` - - * Install OctoPrint in `"editable" mode `_, - including its regular *and* development and plugin development dependencies: - - * ``pip install -e '.[develop,plugins]'`` - .. _sec-development-environment-source-linux: Linux @@ -94,14 +69,14 @@ Linux This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. -First make sure you have python 2 and 3 including their header files, pip, setuptools, virtualenv, git and some build requirements +First make sure you have python 3 including its header files, pip, setuptools, virtualenv, git and some build requirements installed: * On apt based distributions (e.g. Debian, Ubuntu, ...): .. code-block:: none - sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential + sudo apt-get install python3 python3-pip python3-dev python3-setuptools python3-virtualenv git libyaml-dev build-essential Then: @@ -110,36 +85,13 @@ Then: cd ~/devel git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv --python=python3 venv3 - source ./venv3/bin/activate + virtualenv --python=python3 venv + source ./venv/bin/activate pip install --upgrade pip pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs -.. _sec-development-environment-linux-python2: - -Optional Python 2 environment -............................. - -If a Python 2 environment is also desired: - - * On apt based distributions (e.g. Debian, Ubuntu, ...): - - .. code-block:: none - - sudo apt-get install python2 python2-dev python-pip python-setuptools python-virtualenv - -Then: - -.. code-block:: none - - virtualenv --python=python2 venv2 - source ./venv2/bin/activate - pip install --upgrade pip - pip install -e '.[develop,plugins]' - -You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments. .. todo:: @@ -180,38 +132,13 @@ Open the Git Bash you just installed and in that: cd /c/Devel git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv --python=C:/Python3/python.exe venv3 - source ./venv3/Scripts/activate + virtualenv --python=C:/Python3/python.exe venv + source ./venv/Scripts/activate pip install --upgrade pip python -m pip install -e '.[develop,plugins,docs]' pre-commit install git config blame.ignoreRevsFile .git-blame-ignore-revs -.. _sec-development-environment-windows-python2: - -Optional Python 2 environment -............................. - -If a Python 2 environment is also desired, then also download and install - - * `Python 2.7.18 MSI installer `_ (mirrored on octoprint.org) - - * it's recommended to install Python 2.7 into ``C:\Python27`` - if you select - different install locations please substitute accordingly - * it's also recommended to install for all users - - * `Microsoft Visual C++ Compiler for Python 2.7 `_ (mirrored on octoprint.org) - -Then: - -.. code-block:: none - - cd /c/Devel/OctoPrint - virtualenv --python=C:/Python27/python.exe venv2 - source ./venv2/Scripts/activate - python -m pip install --upgrade pip - pip install -e '.[develop,plugins]' - .. _sec-development-environment-windows-optional: Optional but recommended tools @@ -248,12 +175,6 @@ Mac OS X This guide is based on the `Setup Guide for Mac OS X on OctoPrint's Community Forum `_. Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks. -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2 and 3 environments during development. Please send a - `Pull Request `_ to get the necessary - steps into this guide! - This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -266,7 +187,7 @@ You'll need a user account with administrator privileges. * ``sudo xcodebuild`` (ensure the license was accepted) * If you have more than one Xcode installed: ``sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`` - * Install Homebrew and use that to install Python: + * Install Homebrew and use that to install Python 3: * ``ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`` * ``brew install python`` @@ -313,11 +234,11 @@ PyCharm - Register virtual environments: - **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", - select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3`` or ``C:\Devel\OctoPrint\venv3``). + select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``). - **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." > - "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv3`` folder (e.g. ``~/devel/OctoPrint/venv3``). + "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv`` folder (e.g. ``~/devel/OctoPrint/venv``). - If desired, repeat for the ``venv2`` folder, or any other additional Python venvs. + If desired, repeat for any other additional Python venvs (e.g. for separate Python 3 versions). - Right click "src" in project tree, mark as source folder - Add Run/Debug Configuration, select "Python": @@ -362,7 +283,7 @@ PyCharm * Module name: ``sphinx.cmd.build`` * Parameters: ``-v -T -E ./docs ./docs/_build -b html`` * Project: ``OctoPrint`` - * Python interpreter: ``venv3`` environment (the docs build requires Python 3) + * Python interpreter: ``venv`` environment * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * Just like with the run configuration for the server you can also have the dependencies auto-update when building the documentation, see above on how to set this up. @@ -375,14 +296,14 @@ PyCharm * Name: pre-commit * File type: Python * Scope: Module 'OctoPrint' - * Program: ``/bin/pre-commit`` (Linux) or ``/Scripts/pre-commit`` (Windows) + * Program: ``/bin/pre-commit`` (Linux) or ``/Scripts/pre-commit`` (Windows) * Arguments: ``run --hook-stage manual --files $FilePath$`` * Output paths to refresh: ``$FilePath$`` * Working directory: ``$ProjectFileDir$`` * disable "Auto-save edited files to trigger the watched" * enable "Trigger the watched on external changes" -To switch between virtual environments (e.g. Python 3 and 2), all you need to do now is change the Project Default Interpreter and restart +To switch between virtual environments (e.g. Python 3.7 and 3.8), all you need to do now is change the Project Default Interpreter and restart OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE. Otherwise go through Settings. @@ -406,7 +327,7 @@ Visual Studio Code (vscode) .. code-block:: json { - "python.defaultInterpreterPath": "venv3/bin/python", + "python.defaultInterpreterPath": "venv/bin/python", "python.formatting.provider": "black", "python.formatting.blackArgs": [ "--config", @@ -466,7 +387,7 @@ Visual Studio Code (vscode) } ] } - + In the terminal install the python extension by running this command: .. code-block:: bash @@ -486,7 +407,7 @@ Visual Studio Code (vscode) * Your terminal inside vscode uses the virtual python environment * Saving a file will run an auto formatter and import sort - + * ``Ctrl+Shift+B`` can be used to run the ``build docs`` task to rebuild the documentation - + diff --git a/docs/plugins/controlproperties.rst b/docs/plugins/controlproperties.rst index c8ac018a0..b5905fa07 100644 --- a/docs/plugins/controlproperties.rst +++ b/docs/plugins/controlproperties.rst @@ -57,10 +57,13 @@ The following properties are recognized: ``__plugin_pythoncompat__`` Python compatibility string of your plugin, optional, defaults to ``>=2.7,<3`` if not set and thus Python 2 but no - Python 3 compatibility. + Python 3 compatibility. This is used as a precaution against issues with some of the Python 2 only plugins + that are still out there, as OctoPrint will not even attempt to load plugins whose Python compatibility + information doesn't match its current environment. - If your plugin is compatible to Python 3, you should set this to ``>=2.7,<4``, otherwise your plugin will not load - on OctoPrint instances installed under Python 3. + If your plugin is compatible to Python 3 only, you should set this to ``>=3.7,<4``. + + If your plugin is compatible to Python 2 and Python 3, you should set this to ``>=2.7,<4``. .. code-block:: python diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 3ac2939d5..41765ab83 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -57,13 +57,10 @@ We'll start at the most basic form a plugin can take - just a few simple lines o .. code-block:: python :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup:: @@ -81,8 +78,9 @@ OctoPrint found that plugin in the folder and took a look into it. The name and entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from ``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now. Additionally there is ``__plugin_pythoncompat__`` which tells OctoPrint here that your plugin can be run under any Python versions -between 2.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under either -Python 2 or Python 3, and compatibility to both should be your goal. +between 3.7 and 4. That is necessary so that your plugin will be loadable in OctoPrint instances running under Python 3 +but not Python 2 (so you can use modern language features), and going forward you really should no longer have to care about +the end-of-life Python 2. .. _sec-plugins-gettingstarted-sayinghello: @@ -96,9 +94,6 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t :emphasize-lines: 4-8,14 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin): @@ -108,7 +103,7 @@ Apart from being discovered by OctoPrint, our plugin does nothing yet. We want t __plugin_name__ = "Hello World" __plugin_version__ = "1.0.0" __plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() and restart OctoPrint. You now get this output in the log:: @@ -297,16 +292,13 @@ and ``__plugin_description__`` from ``__init__.py``, but leave ``__plugin_implem .. code-block:: python :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin): def on_after_startup(self): self._logger.info("Hello World!") - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() and restart OctoPrint:: @@ -320,12 +312,9 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the "OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again: .. code-block:: python - :emphasize-lines: 10 + :emphasize-lines: 7 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin): @@ -333,7 +322,7 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the self._logger.info("Hello World!") __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() @@ -369,12 +358,9 @@ navigation bar right at the top that links to the Wikipedia node about "Hello Wo add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: .. code-block:: python - :emphasize-lines: 7 + :emphasize-lines: 4 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -383,7 +369,7 @@ add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class: self._logger.info("Hello World!") __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file @@ -436,12 +422,9 @@ mixin. Let's take a look at how all that would look in our plugin's ``__init__.py``: .. code-block:: python - :emphasize-lines: 8, 10, 12-13 + :emphasize-lines: 5, 7, 9-10 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -454,7 +437,7 @@ Let's take a look at how all that would look in our plugin's ``__init__.py``: return dict(url="https://en.wikipedia.org/wiki/Hello_world") __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() Restart OctoPrint. You should see something like this:: @@ -471,12 +454,9 @@ to add our URL as a template variable. Adjust your plugin's ``__init__.py`` like this: .. code-block:: python - :emphasize-lines: 15-16 + :emphasize-lines: 12-13 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -492,7 +472,7 @@ Adjust your plugin's ``__init__.py`` like this: return dict(url=self._settings.get(["url"])) __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this: @@ -579,12 +559,9 @@ for both our ``navbar`` and our ``settings`` plugin. We'll also remove the overr again since we don't use that anymore: .. code-block:: python - :emphasize-lines: 15-19 + :emphasize-lines: 12-16 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -603,7 +580,7 @@ again since we don't use that anymore: ] __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we @@ -677,12 +654,9 @@ just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its me like so: .. code-block:: python - :emphasize-lines: 9,22-25 + :emphasize-lines: 6,19-22 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -707,7 +681,7 @@ like so: ) __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`. @@ -858,12 +832,9 @@ Then adjust our plugin's ``__init__.py`` so that the :func:`~octoprint.plugin.As a reference to our CSS file: .. code-block:: python - :emphasize-lines: 26 + :emphasize-lines: 23 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -890,7 +861,7 @@ a reference to our CSS file: ) __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() OctoPrint by default bundles all CSS, JavaScript and LESS files to reduce the amount of requests necessary to fully @@ -944,12 +915,9 @@ in the process. The folder structure of our plugin should now look like this:: Then adjust our returned assets to include our LESS file as well: .. code-block:: python - :emphasize-lines: 27 + :emphasize-lines: 24 :linenos: - # -*- coding: utf-8 -*- - from __future__ import absolute_import, unicode_literals - import octoprint.plugin class HelloWorldPlugin(octoprint.plugin.StartupPlugin, @@ -977,7 +945,7 @@ Then adjust our returned assets to include our LESS file as well: ) __plugin_name__ = "Hello World" - __plugin_pythoncompat__ = ">=2.7,<4" + __plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = HelloWorldPlugin() diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 1f65e91af..8a78c7785 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -28,7 +28,6 @@ or as ``postfix`` (after the existing lines). .. code-block:: python :linenos: - from past import basestring self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.scripts") # ... @@ -45,7 +44,7 @@ or as ``postfix`` (after the existing lines). continue def to_list(data): - if isinstance(data, basestring): + if isinstance(data, str): data = map(x.strip() for x in data.split("\n")) if isinstance(data, (list, tuple)): diff --git a/docs/plugins/python3_migration.rst b/docs/plugins/python3_migration.rst index 170e039e7..1a85d2dc0 100644 --- a/docs/plugins/python3_migration.rst +++ b/docs/plugins/python3_migration.rst @@ -211,7 +211,7 @@ NOT need to convert to bytes when implementing API endpoints that return JSON, a anyhow. OctoPrint includes two utility methods you should use to ensure your strings enter/exit your code in the right format, -under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_unicode`. Use them to ensure the correct data +under both Python versions: :py:func:`octoprint.util.to_bytes` and :py:func:`octoprint.util.to_str`. Use them to ensure the correct data types and to avoid weird conversion and encoding issues during runtime. You can read more about this specific issue in the corresponding section of the diff --git a/run b/run deleted file mode 100755 index 8646c57a3..000000000 --- a/run +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -import os -import sys - -basedir = os.path.dirname(os.path.realpath(__file__)) - -old = os.path.join(basedir, "octoprint") -if os.path.exists(old): - # rename left-overs from old file structure - print( - """ -Found left-overs from old file structure, renaming to -"octoprint.backup". Please remove this manually (I don't -dare to do so myself since you might have changes in there -I don't know anything about). -""" - ) - os.rename(old, os.path.join(basedir, "octoprint.backup")) - -sys.path.insert(0, os.path.join(basedir, "src")) - -import octoprint # noqa: E402 - -if len(sys.argv) == 1: - sys.argv.append("serve") -octoprint.main() diff --git a/setup.py b/setup.py index 083ce8fbe..919299b6f 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,14 @@ -#!/usr/bin/env python2 # -*- coding: utf-8 -*- +### NOTE ################################################################################# +# This file has to stay format compatible to Python 2, or pip under Python 2 will +# not be able to detect that OctoPrint requires Python 3 but instead fail with a +# syntax error. +# +# So, no f-strings, no walrus operators, no pyupgrade or codemods. +########################################################################################## + import os -import re import sys from distutils.command.build_py import build_py as _build_py @@ -19,7 +25,7 @@ import octoprint_setuptools # noqa: F401,E402 PYTHON_REQUIRES = ">=3.7, <4" # Requirements for setup.py -SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3 +SETUP_REQUIRES = ["markdown>=3.2.2,<4"] # Requirements for our application INSTALL_REQUIRES = [ @@ -27,25 +33,19 @@ INSTALL_REQUIRES = [ "OctoPrint-FileCheck>=2021.2.23", "OctoPrint-FirmwareCheck>=2021.10.11", "OctoPrint-PiSupport>=2021.10.28", - # the following dependencies are non trivial to update since later versions - # introduce backwards incompatible changes that might affect plugins, or due to - # other observed problems - "markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3 - "markdown>=3.1,<3.2", # newer versions require Python 3 - "wrapt>=1.12.1,<1.13", # newer versions fail to build on OctoPi 0.15 # anything below this should be checked on releases for new versions - "flask>=1.1.4,<2", # newer versions require Python 3 - "Jinja2>=2.11.3,<3", # newer versions require Python 3 + "wrapt>=1.13.3,<1.14", + "tornado>=6.0.4,<7", + "markdown>=3.2.2,<4", + "flask>=2,<3", "Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases - "Flask-Babel>=1.0,<2", # newer versions require Python 3 + "Flask-Babel>=2.0,<3", "Flask-Assets>=2.0,<3", - "werkzeug>=1.0.1,<2", # newer versions require Python 3 - "itsdangerous>=1.1.0,<2", # newer versions require Python 3 - "cachelib>=0.1,<0.2", # newer versions require Python 3 + "cachelib>=0.2,<0.3", "PyYAML>=5.4.1,<6", "pyserial>=3.4,<4", "netaddr>=0.8,<0.9", # changelog hints at breaking changes on minor version increases - "watchdog==0.10.4", # newer versions require Python 3 + "watchdog==1.0.0", "sarge==0.1.6", "netifaces>=0.11,<1", "pylru>=1.2,<2", @@ -53,44 +53,21 @@ INSTALL_REQUIRES = [ "requests>=2.26.0,<3", "semantic_version>=2.8.5,<3", "psutil>=5.8,<6", - "Click>=7.1.2,<8", # newer versions require Python 3 - "future>=0.18.2,<1", - "websocket-client>=0.59,<1", # newer versions require Python 3 + "Click>=8.0.3,<9", + "future>=0.18.2,<1", # not really needed anymore, but leaving in for py2/3 compat plugins + "websocket-client>=1.2.1,<2", "emoji>=1.4.2,<2", "sentry-sdk>=1.3.1,<2", "filetype>=1.0.7,<2", "zipstream-new>=1.1.8,<1.2", - # vendor bundled dependencies - "blinker>=1.4,<2", # dependency of flask_principal -] - -# Python 2 specific requirements -INSTALL_REQUIRES_PYTHON2 = [ - "feedparser>=5.2.1,<6", # newer versions require Python 3 - "tornado==5.1.1", # newer versions require Python 3 - "futures>=3.3,<4", - "monotonic>=1.6,<2", - "scandir>=1.10,<2", - "chainmap>=1.0.3,<2", - "typing>=3.10.0.0,<4", - "enum34>=1.1.10,<1.2", - "frozendict==1.2", # newer versions require Python 3 - "colorlog<5", # newer versions require Python 3 - # vendor bundled dependencies - "unidecode<1.3", # dependency of awesome-slugify, newer versions require Python 3 - "regex<2022.1.18", # dependency of awesome-slugify, newer versions require Python 3 -] - -# Python 3 specific requirements -INSTALL_REQUIRES_PYTHON3 = [ "feedparser>=6.0.8,<7", - "tornado>=6,<7", # tornado < 6 is incompatible with Python 3.10 "zeroconf>=0.33,<0.34", # breaking changes can happen on minor version increases "frozendict>=2.0,<3", "pathvalidate>=2.4.1,<3", "colorlog>=5.0.1,<6", # vendor bundled dependencies - "unidecode", # dependency of awesome-slugify, leave w/o range to not cause dependency hell w/ Octolapse deps + "blinker>=1.4,<2", # dependency of flask_principal + "unidecode", # dependency of awesome-slugify "regex", # dependency of awesome-slugify ] @@ -103,10 +80,8 @@ INSTALL_REQUIRES_OSX = [ EXTRA_REQUIRES = { "develop": [ # Testing dependencies - "mock>=3.0.5,<4 ; python_version < '3'", - "pytest==4.6.10 ; python_version < '3'", - "mock>=4,<5 ; python_version >= '3'", - "pytest>=6.2.5,<7 ; python_version >= '3'", + "mock>=4,<5", + "pytest>=6.2.5,<7", "pytest-doctest-custom>=1.0.0,<2", "ddt", # pre-commit @@ -129,41 +104,7 @@ EXTRA_REQUIRES = { # Dependency links for any of the aforementioned dependencies DEPENDENCY_LINKS = [] -# adapted from https://hynek.me/articles/conditional-python-dependencies/ -if int(setuptools.__version__.split(".", 1)[0]) < 18: - # no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies - # would get lost there - assert "bdist_wheel" not in sys.argv - - # add optional dependencies for setuptools versions < 18 that don't yet support environment markers - def _filter_by_python_version_marker(requirements): - for requirement in requirements: - req_match = re.match( - r"^(?P.+);\s*(?Ppython_version.+)$", requirement - ) - if not req_match: - yield requirement - else: - if eval(req_match.group("marker"), {}, {"python_version": sys.version}): - yield req_match.group("req") - - EXTRA_REQUIRES = { - extra: list(_filter_by_python_version_marker(extra_requirements)) - for extra, extra_requirements in EXTRA_REQUIRES.items() - } - - if sys.version_info[0] < 3: - INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 - else: - INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3 - - if sys.platform == "darwin": - INSTALL_REQUIRES += INSTALL_REQUIRES_OSX -else: - # environment markers supported - EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 - EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3 - EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX +EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX # ----------------------------------------------------------------------------------------------------------------------- # Anything below here is just command setup and general setup configuration @@ -172,9 +113,9 @@ here = os.path.abspath(os.path.dirname(__file__)) def read_file_contents(path): - import codecs + import io - with codecs.open(path, encoding="utf-8") as f: + with io.open(path, encoding="utf-8") as f: return f.read() @@ -286,10 +227,7 @@ def params(): "Natural Language :: German", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", @@ -328,8 +266,7 @@ def params(): if os.environ.get("READTHEDOCS", None) == "True": # we can't tell read the docs to please perform a pip install -e .[docs], so we help - # it a bit here by explicitly adding the development dependencies, which include our - # documentation dependencies + # it a bit here by explicitly adding the docs dependencies install_requires = install_requires + extras_require["docs"] entry_points = {"console_scripts": ["octoprint = octoprint:main"]} diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 86940e08d..b49673e3e 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals import logging as log import os @@ -30,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 @@ -421,7 +396,7 @@ def octoprint_plugin_inject_factory(settings, components): def wrapper(*args, **kwargs): tags = kwargs.get("tags", set()) | { "source:plugin", - "plugin:{}".format(name), + f"plugin:{name}", } kwargs["tags"] = tags return f(*args, **kwargs) @@ -431,9 +406,7 @@ def octoprint_plugin_inject_factory(settings, components): class TaggedFuncsPrinter(wrapt.ObjectProxy): def __getattribute__(self, attr): - __wrapped__ = super(TaggedFuncsPrinter, self).__getattribute__( - "__wrapped__" - ) + __wrapped__ = super().__getattribute__("__wrapped__") if attr == "__wrapped__": return __wrapped__ @@ -548,7 +521,7 @@ def init_custom_events(plugin_manager): if isinstance(result, (list, tuple)): for event in result: constant, value = octoprint.events.Events.register_event( - event, prefix="plugin_{}_".format(name) + event, prefix=f"plugin_{name}_" ) logger.debug( 'Registered event {} of plugin {} as Events.{} = "{}"'.format( @@ -557,7 +530,7 @@ def init_custom_events(plugin_manager): ) except Exception: logger.exception( - "Error while retrieving custom event list from plugin {}".format(name), + f"Error while retrieving custom event list from plugin {name}", extra={"plugin": name}, ) @@ -684,7 +657,7 @@ def init_pluginsystem( disabled_from_overlays[name] = (disabled_plugins, order) settings_overlays[name] = overlay - logger.debug("Found settings overlay on plugin {}".format(name)) + logger.debug(f"Found settings overlay on plugin {name}") def handle_plugins_loaded( startup=False, initialize_implementations=True, force_reload=None @@ -726,7 +699,7 @@ def init_pluginsystem( def handle_plugin_enabled(name, plugin): if name in settings_overlays: settings.add_overlay(settings_overlays[name]) - logger.info("Added settings overlay from plugin {}".format(name)) + logger.info(f"Added settings overlay from plugin {name}") pm.on_plugin_loaded = handle_plugin_loaded pm.on_plugins_loaded = handle_plugins_loaded @@ -753,7 +726,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): format_entry = ( lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 - else "{} (any)".format(x) + else f"{x} (any)" ) return ", ".join(map(format_entry, entries)) @@ -792,7 +765,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): ) ) for version in entry["versions"]: - result.append((entry["plugin"], "=={}".format(version))) + result.append((entry["plugin"], f"=={version}")) else: logger.debug("Blacklisted plugin: {}".format(entry["plugin"])) result.append(entry["plugin"]) @@ -954,10 +927,6 @@ def main(): # cut off stuff from the beginning args = args[-1 * sys_args_length :] if sys_args_length else [] - from octoprint.util.fixes import patch_sarge_async_on_py2 - - patch_sarge_async_on_py2() - from octoprint.cli import octo octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") diff --git a/src/octoprint/__main__.py b/src/octoprint/__main__.py index 865fcc44e..176c56e2f 100644 --- a/src/octoprint/__main__.py +++ b/src/octoprint/__main__.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals if __name__ == "__main__": import octoprint diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 3884142d1..bff3b84f6 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -13,7 +10,6 @@ from __future__ import absolute_import, division, print_function, unicode_litera """Git implementation of _version.py.""" import errno -import io import logging import os import re @@ -90,7 +86,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 @@ -100,7 +96,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried {}".format(commands)) + print(f"unable to find command, tried {commands}") return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -143,7 +139,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = io.open(versionfile_abs, "rt", encoding="utf-8") + f = open(versionfile_abs, encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -154,7 +150,7 @@ def git_get_keywords(versionfile_abs): if mo: keywords["full"] = mo.group(1) f.close() - except EnvironmentError: + except OSError: pass return keywords @@ -337,7 +333,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with io.open(path, "rt", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: for line in f: if "#" in line: line = line[: line.index("#")] diff --git a/src/octoprint/access/__init__.py b/src/octoprint/access/__init__.py index 599123f9b..a90c18f32 100644 --- a/src/octoprint/access/__init__.py +++ b/src/octoprint/access/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - ADMIN_GROUP = "admins" USER_GROUP = "users" GUEST_GROUP = "guests" diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index a461cb299..2b5671234 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Marc Hannappel " __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" @@ -9,8 +6,6 @@ import logging import os from functools import partial -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 @@ -24,10 +19,10 @@ GroupNeed.__doc__ = """A need with the method preset to `"group"`.""" class GroupPermission(Permission): def __init__(self, key): need = GroupNeed(key) - super(GroupPermission, self).__init__(need) + super().__init__(need) -class GroupManager(object): +class GroupManager: @classmethod def default_permissions_for_group(cls, group): result = [] @@ -178,7 +173,7 @@ class GroupManager(object): # noinspection PyCompatibility if isinstance(group, Group): return group - elif isinstance(group, basestring): + elif isinstance(group, str): return self.find_group(group) elif isinstance(group, dict): return self.find_group(group.get("key")) @@ -186,17 +181,17 @@ class GroupManager(object): return None def _notify_listeners(self, action, group, *args, **kwargs): - method = "on_group_{}".format(action) + method = f"on_group_{action}" for listener in self._group_change_listeners: try: getattr(listener, method)(group, *args, **kwargs) except Exception: self._logger.exception( - "Error notifying listener {!r} via {}".format(listener, method) + f"Error notifying listener {listener!r} via {method}" ) -class GroupChangeListener(object): +class GroupChangeListener: def on_group_added(self, group): pass @@ -318,7 +313,7 @@ class FilebasedGroupManager(GroupManager): except Exception: self._logger.exception( - "Error while loading groups from file {}".format(self._groupfile) + f"Error while loading groups from file {self._groupfile}" ) def _save(self, force=False): @@ -522,7 +517,7 @@ class GroupCantBeChanged(Exception): Exception.__init__(self, "Group can't be changed: %s" % key) -class Group(object): +class Group: def __init__( self, key, diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index 601e1e365..b41923009 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Marc Hannappel " __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" @@ -12,9 +9,6 @@ from flask import abort, g from flask_babel import gettext from future.utils import with_metaclass -# noinspection PyCompatibility -from past.builtins import basestring - from octoprint.access import ADMIN_GROUP, READONLY_GROUP, USER_GROUP from octoprint.vendor.flask_principal import Need, Permission, PermissionDenied, RoleNeed @@ -37,7 +31,7 @@ class OctoPrintPermission(Permission): result.append(need) elif isinstance(need, Permission): result += need.needs - elif isinstance(need, basestring): + elif isinstance(need, str): result.append(RoleNeed(need)) return result @@ -149,7 +143,7 @@ class PluginOctoPrintPermission(OctoPrintPermission): return result -class PluginIdentityContext(object): +class PluginIdentityContext: """Identity context for not initialized Permissions Needed to support @Permissions.PLUGIN_X_Y.require() @@ -254,7 +248,7 @@ class PermissionsMetaClass(type): key = p.key elif isinstance(p, dict): key = p.get("key") - elif isinstance(p, basestring): + elif isinstance(p, str): key = p if key is None: diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index a19c4ce3b..ee2484a45 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -1,20 +1,14 @@ -# -*- 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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import hashlib import logging import os +import time import uuid -# noinspection PyCompatibility -from builtins import bytes, range - import wrapt from flask_login import AnonymousUserMixin, UserMixin -from past.builtins import basestring from werkzeug.local import LocalProxy from octoprint.access.groups import Group, GroupChangeListener @@ -22,10 +16,12 @@ 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, yaml +from octoprint.util import to_bytes, yaml + +# noinspection PyCompatibility -class UserManager(GroupChangeListener, object): +class UserManager(GroupChangeListener): def __init__(self, group_manager, settings=None): self._group_manager = group_manager self._group_manager.register_listener(self) @@ -85,11 +81,11 @@ class UserManager(GroupChangeListener, object): listener.on_user_logged_in(user) except Exception: self._logger.exception( - "Error in on_user_logged_in on {!r}".format(listener), + f"Error in on_user_logged_in on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged in user: {}".format(user.get_id())) + self._logger.info(f"Logged in user: {user.get_id()}") return user @@ -123,17 +119,17 @@ class UserManager(GroupChangeListener, object): listener.on_user_logged_out(user, stale=stale) except Exception: self._logger.exception( - "Error in on_user_logged_out on {!r}".format(listener), + f"Error in on_user_logged_out on {listener!r}", extra={"callback": fqcn(listener)}, ) - self._logger.info("Logged out user: {}".format(user.get_id())) + self._logger.info(f"Logged out user: {user.get_id()}") def _cleanup_sessions(self): for session, user in list(self._session_users_by_session.items()): if not isinstance(user, SessionUser): continue - if user.created + (24 * 60 * 60) < monotonic_time(): + if user.created + (24 * 60 * 60) < time.monotonic(): self._logger.info( "Cleaning up user session {} for user {}".format( session, user.get_id() @@ -271,9 +267,7 @@ class UserManager(GroupChangeListener, object): return False def on_group_removed(self, group): - self._logger.debug( - "Group {} got removed, removing from all users".format(group.key) - ) + self._logger.debug(f"Group {group.key} got removed, removing from all users") self.remove_groups_from_users([group]) def on_group_permissions_changed(self, group, added=None, removed=None): @@ -284,7 +278,7 @@ class UserManager(GroupChangeListener, object): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -297,12 +291,12 @@ class UserManager(GroupChangeListener, object): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) def _trigger_on_user_modified(self, user): - if isinstance(user, basestring): + if isinstance(user, str): # user id users = [] try: @@ -329,7 +323,7 @@ class UserManager(GroupChangeListener, object): listener.on_user_modified(user) except Exception: self._logger.exception( - "Error in on_user_modified on {!r}".format(listener), + f"Error in on_user_modified on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -339,7 +333,7 @@ class UserManager(GroupChangeListener, object): listener.on_user_removed(username) except Exception: self._logger.exception( - "Error in on_user_removed on {!r}".format(listener), + f"Error in on_user_removed on {listener!r}", extra={"callback": fqcn(listener)}, ) @@ -479,7 +473,7 @@ class UserManager(GroupChangeListener, object): )(has_been_customized) -class LoginStatusListener(object): +class LoginStatusListener: def on_user_logged_in(self, user): pass @@ -544,7 +538,7 @@ class FilebasedUserManager(UserManager): # 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) + f"Migrating user {name} to new granular permission system" ) groups |= set(self._migrate_roles_to_groups(attributes["roles"])) @@ -1023,7 +1017,7 @@ class CorruptUserStorage(Exception): ##~~ Refactoring helpers -class MethodReplacedByBooleanProperty(object): +class MethodReplacedByBooleanProperty: def __init__(self, name, message, getter): self._name = name self._message = message @@ -1391,8 +1385,8 @@ class SessionUser(wrapt.ObjectProxy): wrapt.ObjectProxy.__init__(self, user) self._self_session = "".join("%02X" % z for z in bytes(uuid.uuid4().bytes)) - self._self_created = monotonic_time() - self._self_touched = monotonic_time() + self._self_created = time.monotonic() + self._self_touched = time.monotonic() @property def session(self): @@ -1407,7 +1401,7 @@ class SessionUser(wrapt.ObjectProxy): return self._self_touched def touch(self): - self._self_touched = monotonic_time() + self._self_touched = time.monotonic() @deprecated( "SessionUser.get_session() has been deprecated, use SessionUser.session instead", diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index eeaad2d38..827396249 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -18,7 +15,7 @@ click.disable_unicode_literals_warning = True # ~~ click context -class OctoPrintContext(object): +class OctoPrintContext: """Custom context wrapping the standard options.""" def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False): diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 5e8f8f436..9ecf4d4c7 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -94,7 +91,6 @@ def gcode_command( import time - from octoprint.util import monotonic_time from octoprint.util.gcodeInterpreter import gcode throttle_callback = None @@ -114,13 +110,13 @@ def gcode_command( if len(offsets) < maxt: offsets += [(0, 0)] * (maxt - len(offsets)) - start_time = monotonic_time() + start_time = time.monotonic() progress_callback = None if progress: def progress_callback(percentage): - click.echo("PROGRESS:{}".format(percentage)) + click.echo(f"PROGRESS:{percentage}") interpreter = gcode(progress_callback=progress_callback, incl_layers=layers) @@ -135,7 +131,7 @@ def gcode_command( bed_z=bedz, ) - click.echo("DONE:{}s".format(monotonic_time() - start_time)) + click.echo("DONE:{}s".format(time.monotonic() - start_time)) result = interpreter.get_result() if empty_result(result): diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 51dcbcbd3..329f97264 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -1,14 +1,9 @@ -# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import json import click -from past.builtins import unicode import octoprint_client from octoprint import FatalStartupError, init_settings @@ -109,10 +104,10 @@ def cli(ctx, apikey, host, port, httpuser, httppass, https, prefix): def log_response(response, status_code=True, body=True, headers=False): if status_code: - click.echo("Status Code: {}".format(response.status_code)) + click.echo(f"Status Code: {response.status_code}") if headers: for header, value in response.headers.items(): - click.echo("{}: {}".format(header, value)) + click.echo(f"{header}: {value}") click.echo() if body: click.echo(response.text) @@ -163,14 +158,14 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): """POSTs JSON data to the specified server path, taking the data from the specified file.""" if json_flag or yaml_flag: if json_flag: - with io.open(file_path, "rt") as fp: + with open(file_path) as fp: data = json.load(fp) else: data = yaml.load_from_file(path=file_path) r = ctx.obj.client.post_json(path, data, timeout=timeout) else: - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: data = fp.read() r = ctx.obj.client.post(path, data, timeout=timeout) @@ -187,10 +182,10 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): "str_params", multiple=True, nargs=2, - type=click.Tuple([unicode, unicode]), + type=click.Tuple([str, str]), ) @click.option( - "--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]) + "--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([str, int]) ) @click.option( "--float", @@ -198,7 +193,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): "float_params", multiple=True, nargs=2, - type=click.Tuple([unicode, float]), + type=click.Tuple([str, float]), ) @click.option( "--bool", @@ -206,7 +201,7 @@ def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout): "bool_params", multiple=True, nargs=2, - type=click.Tuple([unicode, bool]), + type=click.Tuple([str, bool]), ) @click.option("--timeout", type=float, default=None, help="Request timeout in seconds") @click.pass_context @@ -233,7 +228,7 @@ def command( "params", multiple=True, nargs=2, - type=click.Tuple([unicode, unicode]), + type=click.Tuple([str, str]), ) @click.option("--file-name", type=click.STRING) @click.option("--content-type", type=click.STRING) @@ -276,7 +271,7 @@ def listen(ctx): click.echo("--- Connection closed!") def on_error(ws, error): - click.echo("!!! Error: {}".format(error)) + click.echo(f"!!! Error: {error}") def on_sent(ws, data): click.echo(">>> {}".format(json.dumps(data))) diff --git a/src/octoprint/cli/common.py b/src/octoprint/cli/common.py index c25162bda..0b4a6d681 100644 --- a/src/octoprint/cli/common.py +++ b/src/octoprint/cli/common.py @@ -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) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index 01f92fd85..7ace969c5 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index 46f39f8f4..a23033780 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -10,8 +7,6 @@ import click click.disable_unicode_literals_warning = True -from past.builtins import basestring - class OctoPrintDevelCommands(click.MultiCommand): """ @@ -38,9 +33,7 @@ class OctoPrintDevelCommands(click.MultiCommand): return log self.command_caller = CommandlineCaller() - self.command_caller.on_log_call = log_util( - lambda x: click.echo(">> {}".format(x)) - ) + self.command_caller.on_log_call = log_util(lambda x: click.echo(f">> {x}")) self.command_caller.on_log_stdout = log_util(click.echo) self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) @@ -58,7 +51,7 @@ class OctoPrintDevelCommands(click.MultiCommand): def _get_commands(self): result = {} for group in self.groups: - for command in self._get_commands_from_prefix_methods("{}_".format(group)): + for command in self._get_commands_from_prefix_methods(f"{group}_"): result[group + self.sep + command.name] = command return result @@ -125,7 +118,7 @@ class OctoPrintDevelCommands(click.MultiCommand): if key in options: val = options[key] else: - if not isinstance(raw, basestring): + if not isinstance(raw, str): raw = str(raw) val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index c7f91f5eb..a19e174c5 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -134,7 +131,7 @@ class OctoPrintPluginCommands(click.MultiCommand): result[name + self.sep + command.name] = command except Exception: self._logger.exception( - "Error while retrieving cli commands for plugin {}".format(name), + f"Error while retrieving cli commands for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 3ee8312c8..dcefd9d07 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -47,7 +44,7 @@ def run_server( PluginTimingsLogHandler.arm_rollover() logger.info(get_divider_line("*")) - logger.info("Starting OctoPrint {}".format(__display_version__)) + logger.info(f"Starting OctoPrint {__display_version__}") if safe_mode: logger.info("Starting in SAFE MODE. Third party plugins will be disabled!") if safe_mode == "flag": @@ -58,7 +55,7 @@ def run_server( reason = "problem during last startup" else: reason = "unknown" - logger.info("Reason for safe mode: {}".format(reason)) + logger.info(f"Reason for safe mode: {reason}") if recorder and len(recorder): logger.info(get_divider_line("-", "Logged during platform initialization:")) @@ -101,7 +98,7 @@ def run_server( log_to_handler(logger, handler, level, message) _log(get_divider_line("-", "Log roll over detected")) - _log("OctoPrint {}".format(__display_version__)) + _log(f"OctoPrint {__display_version__}") if safe_mode: _log("SAFE MODE is active. Third party plugins are disabled!") plugin_manager.log_all_plugins(only_to_handler=handler) diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index efef5d172..39cf0fd13 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -1,12 +1,8 @@ -# -*- 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" import datetime -import io import logging import os @@ -33,7 +29,7 @@ def get_systeminfo( last_safe_mode = {"date": "unknown", "reason": "unknown"} try: if os.path.exists(safe_mode_file): - with io.open(safe_mode_file, "r") as f: + with open(safe_mode_file) as f: last_safe_mode["reason"] = f.readline().strip() last_safe_mode["date"] = ( datetime.datetime.utcfromtimestamp( @@ -190,7 +186,7 @@ def systeminfo_command(ctx, path, **kwargs): if path: # create zip at path zipfilename = os.path.join(path, get_systeminfo_bundle_name()) - click.echo("Writing systeminfo bundle to {}...".format(zipfilename)) + click.echo(f"Writing systeminfo bundle to {zipfilename}...") z = get_systeminfo_bundle( systeminfo, settings.getBaseFolder("logs"), plugin_manager=plugin_manager @@ -201,9 +197,7 @@ def systeminfo_command(ctx, path, **kwargs): f.write(data) except Exception as e: click.echo(str(e), err=True) - click.echo( - "There was an error writing to {}.".format(zipfilename), err=True - ) + click.echo(f"There was an error writing to {zipfilename}.", err=True) ctx.exit(-1) click.echo("Done!") diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index ef32dc41e..78f50cefe 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -128,9 +125,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin): click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.as_dict()))) except UserAlreadyExists: - click.echo( - "A user with the name {} does already exist!".format(username), err=True - ) + click.echo(f"A user with the name {username} does already exist!", err=True) @cli.command(name="remove") @@ -145,9 +140,9 @@ def remove_user_command(ctx, username): if confirm.lower() == "yes": ctx.obj.user_manager.remove_user(username) - click.echo("User {} removed.".format(username)) + click.echo(f"User {username} removed.") else: - click.echo("User {} not removed.".format(username)) + click.echo(f"User {username} not removed.") @cli.command(name="password") @@ -158,9 +153,9 @@ def change_password_command(ctx, username, password): """Change an existing user's password.""" try: ctx.obj.user_manager.change_user_password(username, password) - click.echo("Password changed for user {}.".format(username)) + click.echo(f"Password changed for user {username}.") except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @cli.command(name="activate") @@ -170,14 +165,14 @@ def activate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, True) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) @cli.command(name="deactivate") @@ -187,14 +182,14 @@ def deactivate_command(ctx, username): """Activate a user account.""" try: ctx.obj.user_manager.change_user_activation(username, False) - click.echo("User {} activated.".format(username)) + click.echo(f"User {username} activated.") user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") click.echo("\t{}".format(_user_to_line(user.asDict()))) except UnknownUser: - click.echo("User {} does not exist!".format(username), err=True) + click.echo(f"User {username} does not exist!", err=True) def _print_list(users): diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 94c44ae94..07ac5d091 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ -import io import os import signal import sys @@ -66,9 +62,9 @@ class Daemon: # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() - si = io.open(os.devnull, "rt", encoding="utf-8") - so = io.open(os.devnull, "at+", encoding="utf-8") - se = io.open(os.devnull, "at+", encoding="utf-8") + si = open(os.devnull, encoding="utf-8") + so = open(os.devnull, "at+", encoding="utf-8") + se = open(os.devnull, "at+", encoding="utf-8") os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) @@ -156,15 +152,15 @@ class Daemon: def get_pid(self): """Get the pid from the pidfile.""" try: - with io.open(self.pidfile, "rt", encoding="utf-8") as pf: + with open(self.pidfile, encoding="utf-8") as pf: pid = int(pf.read().strip()) - except (IOError, ValueError): + except (OSError, ValueError): pid = None return pid def set_pid(self, pid): """Write the pid to the pidfile.""" - with io.open(self.pidfile, "wt+", encoding="utf-8") as f: + with open(self.pidfile, "wt+", encoding="utf-8") as f: f.write(str(pid) + "\n") def remove_pidfile(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index 944d5c840..fd4f0053f 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -18,7 +15,7 @@ from octoprint.util.platform import get_os from octoprint.util.version import get_python_version_string -class EnvironmentDetector(object): +class EnvironmentDetector: def __init__(self, plugin_manager): self._plugin_manager = plugin_manager @@ -170,7 +167,7 @@ class EnvironmentDetector(object): dumped_environment = yaml.dump(environment, pretty=True).strip() environment_lines = "\n".join( - map(lambda l: "| {}".format(l), dumped_environment.split("\n")) + map(lambda l: f"| {l}", dumped_environment.split("\n")) ) return "Detected environment is Python {} under {} ({}). Details:\n{}".format( environment["python"]["version"], diff --git a/src/octoprint/events.py b/src/octoprint/events.py index c29e22f50..17ed69b1e 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge , 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 @@ -33,7 +25,7 @@ def all_events(): ] -class Events(object): +class Events: # server STARTUP = "Startup" SHUTDOWN = "Shutdown" @@ -161,7 +153,7 @@ def eventManager(): return _instance -class EventManager(object): +class EventManager: """ Handles receiving events and dispatching them to subscribers """ @@ -169,7 +161,7 @@ class EventManager(object): def __init__(self): self._registeredListeners = collections.defaultdict(list) self._logger = logging.getLogger(__name__) - self._logger_fire = logging.getLogger("{}.fire".format(__name__)) + self._logger_fire = logging.getLogger(f"{__name__}.fire") self._startup_signaled = False self._shutdown_signaled = False @@ -193,12 +185,10 @@ class EventManager(object): self._shutdown_signaled = True eventListeners = self._registeredListeners[event] - self._logger_fire.debug( - "Firing event: {} (Payload: {!r})".format(event, payload) - ) + self._logger_fire.debug(f"Firing event: {event} (Payload: {payload!r})") for listener in eventListeners: - self._logger.debug("Sending action to {!r}".format(listener)) + self._logger.debug(f"Sending action to {listener!r}") try: listener(event, payload) except Exception: @@ -265,9 +255,7 @@ class EventManager(object): return self._registeredListeners[event].append(callback) - self._logger.debug( - "Subscribed listener {!r} for event {}".format(callback, event) - ) + self._logger.debug(f"Subscribed listener {callback!r} for event {event}") def unsubscribe(self, event, callback): """ @@ -285,7 +273,7 @@ class EventManager(object): return self._worker.is_alive() -class GenericEventListener(object): +class GenericEventListener: """ The GenericEventListener can be subclassed to easily create custom event listeners. """ @@ -326,7 +314,7 @@ class DebugEventListener(GenericEventListener): def eventCallback(self, event, payload): GenericEventListener.eventCallback(self, event, payload) - self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload)) + self._logger.debug(f"Received event: {event} (Payload: {payload!r})") class CommandTrigger(GenericEventListener): @@ -373,7 +361,7 @@ class CommandTrigger(GenericEventListener): continue if "enabled" in subscription and not subscription["enabled"]: - self._logger.info("Disabled command trigger: {!r}".format(subscription)) + self._logger.info(f"Disabled command trigger: {subscription!r}") continue events = subscription["event"] @@ -432,7 +420,7 @@ class CommandTrigger(GenericEventListener): def _executeSystemCommand(self, command, debug=False): def commandExecutioner(cmd): if debug: - self._logger.info("Executing system command: {}".format(cmd)) + self._logger.info(f"Executing system command: {cmd}") else: self._logger.info("Executing a system command") # we run this with shell=True since we have to trust whatever diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 9fc753936..6a48a4851 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 logging import os +import time from collections import namedtuple -from past.builtins import basestring - import octoprint.plugin import octoprint.util from octoprint.events import Events, eventManager @@ -223,7 +219,7 @@ class NoSuchStorage(Exception): pass -class FileManager(object): +class FileManager: def __init__( self, analysis_queue, @@ -477,7 +473,7 @@ class FileManager(object): analysis=_analysis, ) - end_time = octoprint.util.monotonic_time() + end_time = time.monotonic() eventManager().fire( Events.SLICING_DONE, { @@ -508,7 +504,7 @@ class FileManager(object): slicer = self._slicing_manager.get_slicer(slicer_name) - start_time = octoprint.util.monotonic_time() + start_time = time.monotonic() eventManager().fire( Events.SLICING_STARTED, { @@ -680,7 +676,7 @@ class FileManager(object): ): if not destinations: destinations = list(self._storage_managers.keys()) - if isinstance(destinations, basestring): + if isinstance(destinations, str): destinations = [destinations] result = {} @@ -954,7 +950,7 @@ class FileManager(object): 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) + f"Could not write recovery data to file {self._recovery_file}" ) def delete_recovery_data(self): @@ -965,7 +961,7 @@ class FileManager(object): os.remove(self._recovery_file) except Exception: self._logger.exception( - "Error deleting recovery data file {}".format(self._recovery_file) + f"Error deleting recovery data file {self._recovery_file}" ) def get_recovery_data(self): @@ -982,7 +978,7 @@ class FileManager(object): return data except Exception: self._logger.exception( - "Could not read recovery data from file {}".format(self._recovery_file) + f"Could not read recovery data from file {self._recovery_file}" ) self.delete_recovery_data() diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index c589cd939..b6c01de93 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -1,20 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 copy import logging - -try: - import queue -except ImportError: - import Queue as queue - -import collections import os +import queue import threading import time @@ -22,7 +14,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, yaml +from octoprint.util import yaml from octoprint.util.platform import CLOSE_FDS EMPTY_RESULT = { @@ -62,7 +54,7 @@ class QueueEntry( """ def __str__(self): - return "{location}:{path}".format(location=self.location, path=self.path) + return f"{self.location}:{self.path}" class AnalysisAborted(Exception): @@ -71,7 +63,7 @@ class AnalysisAborted(Exception): self.reenqueue = reenqueue -class AnalysisQueue(object): +class AnalysisQueue: """ OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped by their machine code type. @@ -137,7 +129,7 @@ class AnalysisQueue(object): callback(entry, result) except Exception: self._logger.exception( - "Error while pushing analysis data to callback {}".format(callback), + f"Error while pushing analysis data to callback {callback}", extra={"callback": fqcn(callback)}, ) eventManager().fire( @@ -151,7 +143,7 @@ class AnalysisQueue(object): ) -class AbstractAnalysisQueue(object): +class AbstractAnalysisQueue: """ The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the :class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis @@ -208,9 +200,7 @@ class AbstractAnalysisQueue(object): """ if settings().get(["gcodeAnalysis", "runAt"]) == "never": - self._logger.debug( - "Ignoring entry {entry} for analysis queue".format(entry=entry) - ) + self._logger.debug(f"Ignoring entry {entry} for analysis queue") return elif high_priority: self._logger.debug( @@ -277,7 +267,7 @@ class AbstractAnalysisQueue(object): while True: (priority, entry, high_priority) = self._queue.get() self._logger.debug( - "Processing entry {} from queue (priority {})".format(entry, priority) + f"Processing entry {entry} from queue (priority {priority})" ) self._active.wait() @@ -296,7 +286,7 @@ class AbstractAnalysisQueue(object): high_priority, ) ) - self._logger.debug("Running analysis of entry {} aborted".format(entry)) + self._logger.debug(f"Running analysis of entry {entry} aborted") self._queue.task_done() self._done.set() else: @@ -312,8 +302,8 @@ class AbstractAnalysisQueue(object): self._current_progress = 0 try: - start_time = monotonic_time() - self._logger.info("Starting analysis of {}".format(entry)) + start_time = time.monotonic() + self._logger.info(f"Starting analysis of {entry}") eventManager().fire( Events.METADATA_ANALYSIS_STARTED, { @@ -329,14 +319,12 @@ class AbstractAnalysisQueue(object): result = self._do_analysis() self._logger.info( "Analysis of entry {} finished, needed {:.2f}s".format( - entry, monotonic_time() - start_time + entry, time.monotonic() - start_time ) ) self._finished_callback(self._current, result) except RuntimeError as exc: - self._logger.error( - "Analysis for {} ran into error: {}".format(self._current, exc) - ) + self._logger.error(f"Analysis for {self._current} ran into error: {exc}") finally: self._current = None self._current_progress = None @@ -443,12 +431,12 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): "octoprint", "analysis", "gcode", - "--speed-x={}".format(speedx), - "--speed-y={}".format(speedy), - "--max-t={}".format(max_extruders), - "--throttle={}".format(throttle), - "--throttle-lines={}".format(throttle_lines), - "--bed-z={}".format(bed_z), + f"--speed-x={speedx}", + f"--speed-y={speedy}", + f"--max-t={max_extruders}", + f"--throttle={throttle}", + f"--throttle-lines={throttle_lines}", + f"--bed-z={bed_z}", ] for offset in offsets[1:]: command += ["--offset", str(offset[0]), str(offset[1])] @@ -494,7 +482,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): p.close() output = p.stdout.text - self._logger.debug("Got output: {!r}".format(output)) + self._logger.debug(f"Got output: {output!r}") result = {} if "ERROR:" in output: diff --git a/src/octoprint/filemanager/destinations.py b/src/octoprint/filemanager/destinations.py index da0e93cf9..ea9496d32 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -1,10 +1,7 @@ -# -*- 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" -class FileDestinations(object): +class FileDestinations: SDCARD = "sdcard" LOCAL = "local" diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index bc7e382ac..9594824b9 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1,40 +1,22 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 copy -import io import logging import os 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 past.builtins import basestring - import octoprint.filemanager -from octoprint.util import ( - atomic_write, - is_hidden_path, - time_this, - to_bytes, - to_unicode, - yaml, -) +from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_str, yaml from octoprint.util.files import sanitize_filename -class StorageInterface(object): +class StorageInterface: """ Interface of storage adapters for OctoPrint. """ @@ -486,7 +468,7 @@ class LocalFileStorage(StorageInterface): """ self._logger = logging.getLogger(__name__) - self.basefolder = os.path.realpath(os.path.abspath(to_unicode(basefolder))) + self.basefolder = os.path.realpath(os.path.abspath(to_str(basefolder))) if not os.path.exists(self.basefolder) and create: os.makedirs(self.basefolder) if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): @@ -512,9 +494,7 @@ class LocalFileStorage(StorageInterface): self._initialize_metadata() def _initialize_metadata(self): - self._logger.info( - "Initializing the file metadata for {}...".format(self.basefolder) - ) + self._logger.info(f"Initializing the file metadata for {self.basefolder}...") old_metadata_path = os.path.join(self.basefolder, "metadata.yaml") backup_path = os.path.join(self.basefolder, "metadata.yaml.backup") @@ -543,7 +523,7 @@ class LocalFileStorage(StorageInterface): self._list_folder(self.basefolder) self._logger.info( - "... file metadata for {} initialized successfully.".format(self.basefolder) + f"... file metadata for {self.basefolder} initialized successfully." ) @property @@ -554,8 +534,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: @@ -625,7 +604,7 @@ class LocalFileStorage(StorageInterface): self, path=None, filter=None, recursive=True, level=0, force_refresh=False ): if path: - path = self.sanitize_path(to_unicode(path)) + path = self.sanitize_path(to_str(path)) base = self.path_in_storage(path) if base: base += "/" @@ -737,7 +716,7 @@ class LocalFileStorage(StorageInterface): if not os.path.exists(source_fullpath): raise StorageError( - "{} in {} does not exist".format(source_name, source_path), + f"{source_name} in {source_path} does not exist", code=StorageError.INVALID_SOURCE, ) @@ -753,7 +732,7 @@ class LocalFileStorage(StorageInterface): and source_fullpath != destination_fullpath ): raise StorageError( - "{} does already exist in {}".format(destination_name, destination_path), + f"{destination_name} does already exist in {destination_path}", code=StorageError.INVALID_DESTINATION, ) @@ -1118,7 +1097,7 @@ class LocalFileStorage(StorageInterface): self._save_metadata(path, metadata) def split_path(self, path): - path = to_unicode(path) + path = to_str(path) split = path.split("/") if len(split) == 1: return "", split[0] @@ -1126,7 +1105,7 @@ class LocalFileStorage(StorageInterface): return self.join_path(*split[:-1]), split[-1] def join_path(self, *path): - return "/".join(map(to_unicode, path)) + return "/".join(map(to_str, path)) def sanitize(self, path): """ @@ -1151,19 +1130,19 @@ class LocalFileStorage(StorageInterface): def canonicalize(self, path): name = None - if isinstance(path, basestring): - path = to_unicode(path) + if isinstance(path, str): + path = to_str(path) if path.startswith(self.basefolder): path = path[len(self.basefolder) :] path = path.replace(os.path.sep, "/") path = path.split("/") if isinstance(path, (list, tuple)): if len(path) == 1: - name = to_unicode(path[0]) + name = to_str(path[0]) path = "" else: - name = to_unicode(path[-1]) - path = self.join_path(*map(to_unicode, path[:-1])) + name = to_str(path[-1]) + path = self.join_path(*map(to_str, path[:-1])) if not path: path = "" @@ -1183,7 +1162,7 @@ class LocalFileStorage(StorageInterface): relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the absolute path including leading ``basefolder`` path. """ - path = to_unicode(path) + path = to_str(path) if len(path): if path[0] == "/": @@ -1206,7 +1185,7 @@ class LocalFileStorage(StorageInterface): return path def _sanitize_entry(self, entry, path, entry_path): - entry = to_unicode(entry) + entry = to_str(entry) sanitized = self.sanitize_name(entry) if sanitized != entry: # entry is not sanitized yet, let's take care of that @@ -1217,16 +1196,14 @@ class LocalFileStorage(StorageInterface): while os.path.exists(sanitized_path): counter += 1 sanitized = self.sanitize_name( - "{}_({}){}".format(sanitized_name, counter, sanitized_ext) + f"{sanitized_name}_({counter}){sanitized_ext}" ) sanitized_path = os.path.join(path, sanitized) try: shutil.move(entry_path, sanitized_path) - self._logger.info( - 'Sanitized "{}" to "{}"'.format(entry_path, sanitized_path) - ) + self._logger.info(f'Sanitized "{entry_path}" to "{sanitized_path}"') return sanitized, sanitized_path except Exception: self._logger.exception( @@ -1241,8 +1218,8 @@ class LocalFileStorage(StorageInterface): def path_in_storage(self, path): if isinstance(path, (tuple, list)): path = self.join_path(*path) - if isinstance(path, basestring): - path = to_unicode(path) + if isinstance(path, str): + path = to_str(path) if path.startswith(self.basefolder): path = path[len(self.basefolder) :] path = path.replace(os.path.sep, "/") @@ -1565,7 +1542,7 @@ class LocalFileStorage(StorageInterface): entry_name, path, entry_path ) if entry_name != new_entry_name or entry_path != new_entry_path: - entry_display = to_unicode(entry_name) + entry_display = to_str(entry_name) entry_name = new_entry_name entry_path = new_entry_path entry_stat = os.stat(entry_path) @@ -1671,7 +1648,7 @@ class LocalFileStorage(StorageInterface): except Exception: # So something went wrong somewhere while processing this file entry - log that and continue self._logger.exception( - "Error while processing entry {}".format(entry_path) + f"Error while processing entry {entry_path}" ) continue @@ -1741,7 +1718,7 @@ class LocalFileStorage(StorageInterface): blocksize = 65536 hash = hashlib.sha1() - with io.open(path, "rb") as f: + with open(path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -1822,7 +1799,7 @@ class LocalFileStorage(StorageInterface): metadata = None with self._get_persisted_metadata_lock(path): if os.path.exists(metadata_path): - with io.open(metadata_path, "rt", encoding="utf-8") as f: + with open(metadata_path, encoding="utf-8") as f: try: metadata = json.load(f) except Exception: diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index dd0942d37..18509fd60 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -12,7 +9,7 @@ from octoprint import UMASK from octoprint.util import atomic_write -class AbstractFileWrapper(object): +class AbstractFileWrapper: """ Wrapper for file representations to save to storages. @@ -75,7 +72,7 @@ class DiskFileWrapper(AbstractFileWrapper): os.chmod(path, permissions) def stream(self): - return io.open(self.path, "rb") + return open(self.path, "rb") class StreamWrapper(AbstractFileWrapper): @@ -128,7 +125,7 @@ class MultiStream(io.RawIOBase): """ def __init__(self, *streams): - io.RawIOBase.__init__(self) + super().__init__() self.streams = streams self.current_stream = 0 @@ -187,7 +184,7 @@ class LineProcessorStream(io.RawIOBase): """ def __init__(self, input_stream): - io.RawIOBase.__init__(self) + super().__init__() self.input_stream = io.BufferedReader(input_stream) self.leftover = bytearray() @@ -242,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 diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index e9131300a..b56ae3444 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -1,10 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -from typing import Union - -from past.builtins import basestring, unicode - from octoprint.logging import filters # noqa: F401 from octoprint.logging import handlers # noqa: F401 @@ -89,17 +82,17 @@ def get_divider_line(c, message=None, length=78, indent=3): Examples: - >>> get_divider_line("-") # doctest: +ALLOW_UNICODE + >>> get_divider_line("-") '------------------------------------------------------------------------------' - >>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE + >>> get_divider_line("=", length=10) '==========' - >>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE + >>> get_divider_line("-", message="Hi", length=10) '--- Hi ---' - >>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE + >>> get_divider_line("-", message="A slightly longer text") '--- A slightly longer text ---------------------------------------------------' - >>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE + >>> get_divider_line("-", message="A slightly longer text", indent=5) '----- A slightly longer text -------------------------------------------------' - >>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE + >>> get_divider_line("-", message="Hello World!", length=10) '--- Hello World!' >>> get_divider_line(None) Traceback (most recent call last): @@ -132,7 +125,7 @@ def get_divider_line(c, message=None, length=78, indent=3): formatted divider line """ - assert isinstance(c, basestring), "c is not text" + assert isinstance(c, str), "c is not text" assert len(c) == 1, "c is not a single character" assert isinstance(length, int), "length is not an int" assert isinstance(indent, int), "indent is not an int" @@ -140,7 +133,7 @@ def get_divider_line(c, message=None, length=78, indent=3): if message is None: return c * length - assert isinstance(message, basestring), "message is not text" + assert isinstance(message, str), "message is not text" space = length - 2 * (indent + 1) if space >= len(message): @@ -149,19 +142,18 @@ def get_divider_line(c, message=None, length=78, indent=3): return c * indent + " " + message -def prefix_multilines(text, prefix=": "): - # type: (Union[unicode, bytes], unicode) -> unicode - from octoprint.util import to_unicode +def prefix_multilines(text: str, prefix: str = ": ") -> str: + from octoprint.util import to_str lines = text.splitlines() if not lines: return "" if len(lines) == 1: - return to_unicode(lines[0]) + return to_str(lines[0]) return ( - to_unicode(lines[0]) + to_str(lines[0]) + "\n" - + "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:])) + + "\n".join(map(lambda line: prefix + to_str(line), lines[1:])) ) diff --git a/src/octoprint/logging/filters.py b/src/octoprint/logging/filters.py index 6214ceb72..0885a491a 100644 --- a/src/octoprint/logging/filters.py +++ b/src/octoprint/logging/filters.py @@ -1,12 +1,5 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import logging - -try: - from urllib import parse as urlparse -except ImportError: - import urlparse +import urllib.parse class TornadoAccessFilter(logging.Filter): @@ -16,14 +9,14 @@ class TornadoAccessFilter(logging.Filter): if status == 409: - method, url, client = request_line.split() - u = urlparse.urlparse(url) + _, url, _ = request_line.split() + u = urllib.parse.urlparse(url) if u.path in ("/api/printer",): record.levelno = logging.INFO record.levelname = logging.getLevelName(record.levelno) except Exception: logging.getLogger(__name__).exception( - "Error while filtering log record {!r}".format(record) + f"Error while filtering log record {record!r}" ) return logging.Filter.filter(self, record) diff --git a/src/octoprint/logging/handlers.py b/src/octoprint/logging/handlers.py index 665298efa..fe5528715 100644 --- a/src/octoprint/logging/handlers.py +++ b/src/octoprint/logging/handlers.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - # noinspection PyCompatibility import concurrent.futures import logging.handlers @@ -12,7 +9,7 @@ import time class AsyncLogHandlerMixin(logging.Handler): def __init__(self, *args, **kwargs): self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) - super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def emit(self, record): if getattr(self._executor, "_shutdown", False): @@ -25,18 +22,18 @@ class AsyncLogHandlerMixin(logging.Handler): def _emit(self, record): # noinspection PyUnresolvedReferences - super(AsyncLogHandlerMixin, self).emit(record) + super().emit(record) def close(self): self._executor.shutdown(wait=True) - super(AsyncLogHandlerMixin, self).close() + super().close() class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler): def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # clean up old files on handler start if self.backupCount > 0: @@ -49,14 +46,14 @@ class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(OctoPrintLogHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) @classmethod def registerRolloverCallback(cls, callback, *args, **kwargs): cls.rollover_callbacks.append((callback, args, kwargs)) def doRollover(self): - super(OctoPrintLogHandler, self).doRollover() + super().doRollover() for rcb in self.rollover_callbacks: callback, args, kwargs = rcb @@ -81,7 +78,7 @@ class TriggeredRolloverLogHandler( def __init__(self, *args, **kwargs): kwargs["encoding"] = kwargs.get("encoding", "utf-8") - super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.cleanupFiles() def shouldRollover(self, record): @@ -143,7 +140,7 @@ class PluginTimingsLogHandler(TriggeredRolloverLogHandler): class RecordingLogHandler(logging.Handler): def __init__(self, target=None, *args, **kwargs): - super(RecordingLogHandler, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._buffer = [] self._target = target diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 17151e34e..ea728f4bb 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. @@ -12,7 +11,6 @@ registered plugin types. .. autoclass:: PluginSettings :members: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -25,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, to_str # singleton _instance = None @@ -189,7 +187,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() except Exception: logging.getLogger(__name__).exception( - "Error while retrieving preprocessors for plugin {}".format(plugin_key) + f"Error while retrieving preprocessors for plugin {plugin_key}" ) return None @@ -266,7 +264,7 @@ def call_plugin( continue if hasattr(plugin, method): - logger.debug("Calling {} on {}".format(method, plugin._identifier)) + logger.debug(f"Calling {method} on {plugin._identifier}") try: result = getattr(plugin, method)(*args, **kwargs) if callback: @@ -280,7 +278,7 @@ def call_plugin( error_callback(plugin._identifier, plugin, exc) -class PluginSettings(object): +class PluginSettings: """ The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. @@ -604,7 +602,7 @@ class PluginSettings(object): if item in self.deprecated_access_methods: new = self.deprecated_access_methods[item] decorator = deprecated( - "{old} has been renamed to {new}".format(old=item, new=new), + f"{item} has been renamed to {new}", stacklevel=2, ) item = new @@ -620,7 +618,7 @@ class PluginSettings(object): def _func(*args, **kwargs): return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) - _func.__name__ = to_native_str(item) + _func.__name__ = to_str(item) _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None return _func diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 4c6d6e07c..603d859c4 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ In this module resides the core data structures and logic of the plugin system. @@ -18,7 +17,6 @@ In this module resides the core data structures and logic of the plugin system. :members: """ -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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -26,32 +24,18 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import fnmatch 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 -from octoprint.util import sv, time_this, to_unicode +import octoprint.vendor.imp as imp +from octoprint.util import sv, time_this, to_str 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): @@ -85,12 +69,12 @@ def parse_plugin_metadata(path): # we only support parsing plain text source files return result - logger.debug("Parsing plugin metadata from AST of {}".format(path)) + logger.debug(f"Parsing plugin metadata from AST of {path}") try: import ast - with io.open(path, "rb") as f: + with open(path, "rb") as f: root = ast.parse(f.read(), filename=path) assignments = list( @@ -166,12 +150,12 @@ def parse_plugin_metadata(path): except SyntaxError: raise except Exception: - logger.exception("Error while parsing AST from {}".format(path)) + logger.exception(f"Error while parsing AST from {path}") return result -class ControlProperties(object): +class ControlProperties: attr_name = "__plugin_name__" """ Module attribute from which to retrieve the plugin's human readable name. """ @@ -313,7 +297,7 @@ class ModuleOrigin(_ModuleOrigin): """ -class PluginInfo(object): +class PluginInfo: """ The :class:`PluginInfo` class wraps all available information about a registered plugin. @@ -432,9 +416,9 @@ class PluginInfo(object): def __str__(self): if self.version: - return "{name} ({version})".format(name=self.name, version=self.version) + return f"{self.name} ({self.version})" else: - return to_unicode(self.name) + return to_str(self.name) def long_str( self, @@ -475,27 +459,23 @@ class PluginInfo(object): """ if show_enabled: if self.incompatible: - ret = to_unicode(enabled_strs[3]) + ret = to_str(enabled_strs[3]) elif self.blacklisted: - ret = to_unicode(enabled_strs[2]) + ret = to_str(enabled_strs[2]) elif not self.enabled: - ret = to_unicode(enabled_strs[1]) + ret = to_str(enabled_strs[1]) else: - ret = to_unicode(enabled_strs[0]) + ret = to_str(enabled_strs[0]) else: ret = "" - ret += unicode(self) + ret += str(self) if show_bundled: - ret += ( - to_unicode(bundled_strs[0]) - if self.bundled - else to_unicode(bundled_strs[1]) - ) + ret += to_str(bundled_strs[0]) if self.bundled else to_str(bundled_strs[1]) if show_location and self.location: - ret += to_unicode(location_str).format(location=self.location) + ret += to_str(location_str).format(location=self.location) return ret @@ -797,14 +777,12 @@ class PluginInfo(object): try: return parse_plugin_metadata(self.location) except SyntaxError: - self._logger.exception( - "Invalid syntax in plugin file of plugin {}".format(self.key) - ) + self._logger.exception(f"Invalid syntax in plugin file of plugin {self.key}") self.invalid_syntax = True return {} -class PluginManager(object): +class PluginManager: """ The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the system. @@ -1040,7 +1018,7 @@ class PluginManager(object): module_name = None if package: - module_name = "{}.{}".format(package, key) + module_name = f"{package}.{key}" plugin = self._import_plugin_from_module( key, module_name=module_name, folder=folder, bundled=bundled @@ -1064,7 +1042,7 @@ class PluginManager(object): ) ) except Exception: - self.logger.exception("Error processing folder {}".format(folder)) + self.logger.exception(f"Error processing folder {folder}") return added, found @@ -1202,7 +1180,7 @@ class PluginManager(object): else: return None except Exception: - self.logger.exception("Could not locate plugin {key}".format(key=key)) + self.logger.exception(f"Could not locate plugin {key}") return None # Create a simple dummy entry first ... @@ -1220,14 +1198,14 @@ class PluginManager(object): plugin.bundled = bundled if self._is_plugin_disabled(key): - self.logger.info("Plugin {} is disabled.".format(plugin)) + self.logger.info(f"Plugin {plugin} is disabled.") plugin.forced_disabled = True if self._is_plugin_blacklisted(key) or ( plugin.version is not None and self._is_plugin_version_blacklisted(key, plugin.version) ): - self.logger.warning("Plugin {} is blacklisted.".format(plugin)) + self.logger.warning(f"Plugin {plugin} is blacklisted.") plugin.blacklisted = True python_version = get_python_version_string() @@ -1303,7 +1281,7 @@ class PluginManager(object): plugin.bundled = bundled except Exception: - self.logger.exception("Error loading plugin {key}".format(key=key)) + self.logger.exception(f"Error loading plugin {key}") return None if plugin.check(): @@ -1425,7 +1403,7 @@ class PluginManager(object): ): if plugin.blacklisted: self.logger.warning( - "Plugin {} is blacklisted. Not enabling it.".format(plugin) + f"Plugin {plugin} is blacklisted. Not enabling it." ) continue self.enable_plugin( @@ -2042,7 +2020,7 @@ class PluginManager(object): show_enabled=show_enabled, enabled_strs=enabled_str, ), - sorted(self.plugins.values(), key=lambda x: unicode(x).lower()), + sorted(self.plugins.values(), key=lambda x: str(x).lower()), ) ) legend = "Prefix legend: {1} = disabled, {2} = blacklisted, {3} = incompatible".format( @@ -2311,11 +2289,11 @@ def is_sub_path_of(path, parent): def is_editable_install(install_dir, package, module, location): - package_link = os.path.join(install_dir, "{}.egg-link".format(package)) + package_link = os.path.join(install_dir, f"{package}.egg-link") if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) try: - with io.open(package_link, "rt", encoding="utf-8") as f: + with open(package_link, encoding="utf-8") as f: contents = f.readlines() for line in contents: target = os.path.normcase( @@ -2343,10 +2321,8 @@ 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 pass warnings.warn( @@ -2356,7 +2332,7 @@ class EntryPointMetadata(pkginfo.Distribution): ) -class Plugin(object): +class Plugin: """ The parent class of all plugin implementations. diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index bbd698279..b43982670 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent class, :class:`OctoPrintPlugin`. @@ -15,7 +14,6 @@ Please note that the plugin implementation types are documented in the section :members: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -402,7 +400,7 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin): @property def template_folder_key(self): - return "plugin_{}".format(self._identifier) + return f"plugin_{self._identifier}" def get_template_configs(self): """ @@ -1425,9 +1423,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): import flask kwargs = self.get_blueprint_kwargs() - blueprint = flask.Blueprint( - "plugin." + self._identifier, self._identifier, **kwargs - ) + blueprint = flask.Blueprint(self._identifier, self._identifier, **kwargs) # we now iterate over all members of ourselves and look if we find an attribute # that has data originating from one of our decorators - we ignore anything @@ -2055,10 +2051,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 @@ -2081,15 +2074,10 @@ class SlicerPlugin(OctoPrintPlugin): """ import os - try: - from os import scandir - except ImportError: - from scandir import scandir - lms = [os.stat(profile_path).st_mtime] lms += [ os.stat(entry.path).st_mtime - for entry in scandir(profile_path) + for entry in os.scandir(profile_path) if entry.name.endswith(".profile") ] return max(lms) diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index 092cd3e34..e69de29bb 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1,2 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index 1df93cec8..3b3ae1c10 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -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" @@ -126,7 +123,7 @@ class ActionCommandNotificationPlugin( self._notifications.append((time.time(), message)) self._plugin_manager.send_plugin_message(self._identifier, {"message": message}) - self._logger.info("Got a notification: {}".format(message)) + self._logger.info(f"Got a notification: {message}") def _clear_notifications(self): self._notifications = [] @@ -144,7 +141,7 @@ __plugin_disabling_discouraged__ = gettext( " notifications in OctoPrint" ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = ActionCommandNotificationPlugin() __plugin_hooks__ = { "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index 9a53bc10d..8a43d33dc 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -13,7 +10,7 @@ from octoprint.access.permissions import Permissions from octoprint.events import Events -class Prompt(object): +class Prompt: def __init__(self, text): self.text = text self.choices = [] @@ -93,7 +90,7 @@ class ActionCommandPromptPlugin( and self._enable == "always" and self._enable_signal_support ): - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) elif event == Events.DISCONNECTED: self._close_prompt() @@ -133,9 +130,7 @@ class ActionCommandPromptPlugin( choice = data["choice"] if not isinstance(choice, int) or not self._prompt.validate_choice(choice): - return flask.abort( - 400, "{!r} is not a valid value for choice".format(choice) - ) + return flask.abort(400, f"{choice!r} is not a valid value for choice") self._answer_prompt(choice) @@ -211,7 +206,7 @@ class ActionCommandPromptPlugin( subcode=None, tags=None, *args, - **kwargs + **kwargs, ): if gcode != self._command: return @@ -229,7 +224,7 @@ class ActionCommandPromptPlugin( # noinspection PyProtectedMember return comm_instance._emergency_force_send( - cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode + cmd, f"Force-sending {self._command} to the printer", gcode=gcode ) # ~ capability reporting @@ -240,7 +235,7 @@ class ActionCommandPromptPlugin( if capability == self.CAP_PROMPT_SUPPORT and enabled: self._cap_prompt_support = True if self._enable == "detected" and self._enable_signal_support: - self._printer.commands(["{command} P1".format(command=self._command)]) + self._printer.commands([f"{self._command} P1"]) # ~ prompt handling @@ -280,7 +275,7 @@ class ActionCommandPromptPlugin( self._printer.commands([self._command.format(choice=choice)], force=True) else: self._printer.commands( - ["{command} S{choice}".format(command=self._command, choice=choice)], + [f"{self._command} S{choice}"], force=True, ) @@ -295,7 +290,7 @@ __plugin_disabling_discouraged__ = gettext( " confirmation or selection prompts in OctoPrint" ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = ActionCommandPromptPlugin() __plugin_hooks__ = { "octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler, diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 86465af02..42bbe0aa2 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -1,16 +1,11 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" import calendar -import io import os import re -import sys import threading import time from collections import OrderedDict @@ -28,11 +23,9 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import count, monotonic_time, utmify +from octoprint.util import count, utmify from octoprint.util.text import sanitize -PY2 = sys.version_info[0] < 3 - class AnnouncementPlugin( octoprint.plugin.AssetPlugin, @@ -437,9 +430,7 @@ class AnnouncementPlugin( now = time.time() if os.stat(channel_path).st_mtime + ttl > now: d = feedparser.parse(channel_path) - self._logger.debug( - "Loaded channel {} from cache at {}".format(key, channel_path) - ) + self._logger.debug(f"Loaded channel {key} from cache at {channel_path}") return d return None @@ -451,12 +442,12 @@ class AnnouncementPlugin( url = config["url"] try: - start = monotonic_time() + start = time.monotonic() r = requests.get(url, timeout=30) r.raise_for_status() self._logger.info( "Loaded channel {} from {} in {:.2}s".format( - key, config["url"], monotonic_time() - start + key, config["url"], time.monotonic() - start ) ) except Exception: @@ -467,7 +458,7 @@ class AnnouncementPlugin( response = r.text channel_path = self._get_channel_cache_path(key) - with io.open(channel_path, mode="wt", encoding="utf-8") as f: + with open(channel_path, mode="wt", encoding="utf-8") as f: f.write(response) return feedparser.parse(response) @@ -521,7 +512,7 @@ class AnnouncementPlugin( """Retrieve cache path for channel key.""" safe_key = sanitize(key) - return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) + return os.path.join(self.get_plugin_data_folder(), f"{safe_key}.cache") _image_tag_re = re.compile(r"") @@ -529,11 +520,11 @@ _image_tag_re = re.compile(r"") def _strip_images(text): """ - >>> _strip_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + >>> _strip_images("I'm a link and this is an image: foo") "I'm a link and this is an image: " - >>> _strip_images("One and two and three and four \\"four\\"") # doctest: +ALLOW_UNICODE + >>> _strip_images("One and two and three and four \\"four\\"") 'One and two and three and four ' - >>> _strip_images("No images here") # doctest: +ALLOW_UNICODE + >>> _strip_images("No images here") 'No images here' """ return _image_tag_re.sub("", text) @@ -542,9 +533,9 @@ def _strip_images(text): def _replace_images(text, callback): """ >>> callback = lambda img: "foobar" - >>> _replace_images("I'm a link and this is an image: foo", callback) # doctest: +ALLOW_UNICODE + >>> _replace_images("I'm a link and this is an image: foo", callback) "I'm a link and this is an image: foobar" - >>> _replace_images("One and two and three and four \\"four\\"", callback) # doctest: +ALLOW_UNICODE + >>> _replace_images("One and two and three and four \\"four\\"", callback) 'One foobar and two foobar and three foobar and four foobar' """ result = text @@ -560,13 +551,13 @@ _image_src_re = re.compile(r'src=(?P[\'"]*)(?P.*?)(?P=quote)(?=\s+|> def _lazy_images(text, placeholder=None): """ - >>> _lazy_images("I'm a link and this is an image: foo") # doctest: +ALLOW_UNICODE + >>> _lazy_images("I'm a link and this is an image: foo") 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") # doctest: +ALLOW_UNICODE + >>> _lazy_images("I'm a link and this is an image: foo", placeholder="ph.png") 'I\\'m a link and this is an image: \\'foo\\'' - >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") # doctest: +ALLOW_UNICODE + >>> _lazy_images("One and two and three and four \\"four\\"", placeholder="ph.png") 'One and two and three and four four' - >>> _lazy_images("No images here") # doctest: +ALLOW_UNICODE + >>> _lazy_images("No images here") 'No images here' """ if placeholder is None: @@ -580,7 +571,7 @@ def _lazy_images(text, placeholder=None): quote = match.group("quote") quoted_src = quote + src + quote img_tag = img_tag.replace( - match.group(0), 'src="{}" data-src={}'.format(placeholder, quoted_src) + match.group(0), f'src="{placeholder}" data-src={quoted_src}' ) return img_tag @@ -589,17 +580,12 @@ def _lazy_images(text, placeholder=None): def _strip_tags(text): """ - >>> _strip_tags("Hello world<img src='foo.jpg'>") # doctest: +ALLOW_UNICODE + >>> _strip_tags("Hello world<img src='foo.jpg'>") "Hello world<img src='foo.jpg'>" - >>> _strip_tags("> > Foo") # doctest: +ALLOW_UNICODE + >>> _strip_tags("> > Foo") '> > 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): @@ -610,15 +596,15 @@ def _strip_tags(text): self._fed.append(data) def handle_entityref(self, ref): - self._fed.append("&{};".format(ref)) + self._fed.append(f"&{ref};") def handle_charref(self, ref): - self._fed.append("&#{};".format(ref)) + self._fed.append(f"&#{ref};") def get_data(self): return "".join(self._fed) - tag_stripper = TagStripper() if PY2 else TagStripper(convert_charrefs=False) + tag_stripper = TagStripper(convert_charrefs=False) tag_stripper.feed(text) return tag_stripper.get_data() @@ -631,7 +617,7 @@ __plugin_disabling_discouraged__ = gettext( "regarding security or other critical issues concerning OctoPrint." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = AnnouncementPlugin() __plugin_hooks__ = { diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 9811dd97e..e3190ad36 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals - import os import threading +import time from collections import defaultdict import flask @@ -19,13 +17,7 @@ from octoprint.server.util.flask import ( restricted_access, ) from octoprint.settings import valid_boolean_trues -from octoprint.util import ( - ResettableTimer, - atomic_write, - generate_api_key, - monotonic_time, - yaml, -) +from octoprint.util import ResettableTimer, atomic_write, generate_api_key, yaml CUTOFF_TIME = 10 * 60 # 10min POLL_TIMEOUT = 5 # 5 seconds @@ -35,13 +27,13 @@ class AppAlreadyExists(Exception): pass -class PendingDecision(object): +class PendingDecision: def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None): self.app_id = app_id self.app_token = app_token self.user_id = user_id self.user_token = user_token - self.created = monotonic_time() + self.created = time.monotonic() if callable(timeout_callback): self.poll_timeout = ResettableTimer( @@ -62,7 +54,7 @@ class PendingDecision(object): ) -class ReadyDecision(object): +class ReadyDecision: def __init__(self, app_id, app_token, user_id): self.app_id = app_id self.app_token = app_token @@ -78,7 +70,7 @@ class ReadyDecision(object): ) -class ActiveKey(object): +class ActiveKey: def __init__(self, app_id, api_key, user_id): self.app_id = app_id self.api_key = api_key @@ -186,7 +178,7 @@ class AppKeysPlugin( app_token, user_token = self._add_pending_decision(app_name, user_id=user_id) auth_dialog = flask.url_for( "plugin.appkeys.handle_auth_dialog", app_token=app_token, _external=True - ) + ("?user={}".format(user_id) if user_id else "") + ) + (f"?user={user_id}" if user_id else "") self._plugin_manager.send_plugin_message( self._identifier, @@ -407,7 +399,7 @@ class AppKeysPlugin( def _remove_stale_pending(self): with self._pending_lock: - cutoff = monotonic_time() - CUTOFF_TIME + cutoff = time.monotonic() - CUTOFF_TIME len_before = len(self._pending_decisions) self._pending_decisions = list( filter(lambda x: x.created >= cutoff, self._pending_decisions) @@ -510,7 +502,7 @@ class AppKeysPlugin( persisted = yaml.load_from_file(path=self._key_path) except Exception: self._logger.exception( - "Could not load application keys from {}".format(self._key_path) + f"Could not load application keys from {self._key_path}" ) return @@ -535,7 +527,7 @@ class AppKeysPlugin( yaml.save_to_file(to_persist, file=f) except Exception: self._logger.exception( - "Could not write application keys to {}".format(self._key_path) + f"Could not write application keys to {self._key_path}" ) @@ -549,7 +541,7 @@ __plugin_disabling_discouraged__ = gettext( "obtain an API key without you manually copy-pasting it." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = AppKeysPlugin() __plugin_hooks__ = { "octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key, diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 3380f7d13..f7adc08e8 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -21,18 +18,12 @@ 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: zlib = None -import io import json import logging import os @@ -512,7 +503,7 @@ class BackupPlugin( if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo("Creating backup at {}, please wait...".format(filename)) + click.echo(f"Creating backup at {filename}, please wait...") self._create_backup( filename, exclude=exclude, @@ -556,7 +547,7 @@ class BackupPlugin( path = os.path.join(datafolder, path) if not os.path.exists(path): - click.echo("Backup {} does not exist".format(path), err=True) + click.echo(f"Backup {path} does not exist", err=True) sys.exit(-1) archive = tempfile.NamedTemporaryFile(delete=False) @@ -574,7 +565,7 @@ class BackupPlugin( pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"]) def log(line): - click.echo("\t{}".format(line)) + click.echo(f"\t{line}") for plugin in plugins: octoprint_compatible = is_octoprint_compatible( @@ -650,9 +641,9 @@ class BackupPlugin( on_log_error=on_log_error, on_invalid_backup=on_log_error, ): - click.echo("Restored from {}".format(path)) + click.echo(f"Restored from {path}") else: - click.echo("Restoring from {} failed".format(path), err=True) + click.echo(f"Restoring from {path} failed", err=True) return [backup_command, restore_command] @@ -731,12 +722,12 @@ class BackupPlugin( try: os.remove(full_path) except Exception: - self._logger.exception("Could not delete {}".format(filename)) + self._logger.exception(f"Could not delete {filename}") raise def _get_backups(self): backups = [] - for entry in scandir(self.get_plugin_data_folder()): + for entry in os.scandir(self.get_plugin_data_folder()): if is_hidden_path(entry.path): continue if not entry.is_file(): @@ -760,7 +751,7 @@ class BackupPlugin( data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) if os.path.exists(data_file): try: - with io.open(data_file, mode="rt", encoding="utf-8") as f: + with open(data_file, mode="rt", encoding="utf-8") as f: unknown_plugins = json.load(f) assert isinstance(unknown_plugins, list) @@ -835,7 +826,7 @@ class BackupPlugin( return 0 total = 0 - for entry in scandir(path): + for entry in os.scandir(path): if entry.is_dir(): total += cls._get_disk_size(entry.path, ignored=ignored) elif entry.is_file(): @@ -858,7 +849,7 @@ class BackupPlugin( r.raise_for_status() except Exception: logger.exception( - "Error while fetching the plugin repository data from {}".format(url) + f"Error while fetching the plugin repository data from {url}" ) return {} @@ -879,7 +870,7 @@ class BackupPlugin( # prepare pip caller def log(prefix, *lines): for line in lines: - on_log("{} {}".format(prefix, line.rstrip())) + on_log(f"{prefix} {line.rstrip()}") def log_call(*lines): log(">", *lines) @@ -973,7 +964,7 @@ class BackupPlugin( configfile = settings._configfile basedir = settings._basedir - temporary_path = os.path.join(datafolder, ".{}".format(name)) + temporary_path = os.path.join(datafolder, f".{name}") final_path = os.path.join(datafolder, name) own_folder = datafolder @@ -1022,7 +1013,7 @@ class BackupPlugin( return if os.path.isdir(source): - for entry in scandir(source): + for entry in os.scandir(source): add_to_zip( entry.path, os.path.join(target, entry.name), @@ -1168,7 +1159,7 @@ class BackupPlugin( temp = tempfile.mkdtemp() try: if callable(on_log_progress): - on_log_progress("Unpacking backup to {}...".format(temp)) + on_log_progress(f"Unpacking backup to {temp}...") abstemp = os.path.abspath(temp) dirs = {} @@ -1214,7 +1205,7 @@ class BackupPlugin( plugins = [] plugin_list_file = os.path.join(temp, "plugin_list.json") if os.path.exists(plugin_list_file): - with io.open(os.path.join(temp, "plugin_list.json"), "rb") as f: + with open(os.path.join(temp, "plugin_list.json"), "rb") as f: plugins = json.load(f) known_plugins = [] @@ -1264,16 +1255,12 @@ class BackupPlugin( basedir_extracted = os.path.join(temp, "basedir") if callable(on_log_progress): - on_log_progress( - "Renaming {} to {}...".format(basedir, basedir_backup) - ) + on_log_progress(f"Renaming {basedir} to {basedir_backup}...") shutil.move(basedir, basedir_backup) try: if callable(on_log_progress): - on_log_progress( - "Moving {} to {}...".format(basedir_extracted, basedir) - ) + on_log_progress(f"Moving {basedir_extracted} to {basedir}...") shutil.move(basedir_extracted, basedir) except Exception: if callable(on_log_error): @@ -1300,7 +1287,7 @@ class BackupPlugin( datafolder, UNKNOWN_PLUGINS_FILE ) try: - with io.open(unknown_plugins_path, mode="wb") as f: + with open(unknown_plugins_path, mode="wb") as f: f.write(to_bytes(json.dumps(unknown_plugins))) except Exception: if callable(on_log_error): @@ -1354,7 +1341,7 @@ class BackupPlugin( except Exception: if callable(on_log_error): on_log_error( - "Error while restarting via command {}".format(restart_command), + f"Error while restarting via command {restart_command}", exc_info=sys.exc_info(), ) on_log_error("Please restart OctoPrint manually") @@ -1413,7 +1400,7 @@ __plugin_disabling_discouraged__ = gettext( "& restore your OctoPrint settings and data." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = BackupPlugin() __plugin_hooks__ = { "octoprint.server.http.routes": __plugin_implementation__.route_hook, diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 3416ce750..7752d50b4 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -57,9 +54,9 @@ class CoreWizardPlugin( config = { "type": "wizard", "name": name, - "template": "corewizard_{}_wizard.jinja2".format(key), - "div": "wizard_plugin_corewizard_{}".format(key), - "suffix": "_{}".format(key), + "template": f"corewizard_{key}_wizard.jinja2", + "div": f"wizard_plugin_corewizard_{key}", + "suffix": f"_{key}", } if key in additional: additional_result = additional[key]() @@ -136,5 +133,5 @@ __plugin_disabling_discouraged__ = gettext( "setup steps that might be required after an update." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = CoreWizardPlugin() diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index f88575bc7..2a2e04fac 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -11,11 +8,10 @@ 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 -class ServerCommandsSubwizard(object): +class ServerCommandsSubwizard: def _is_servercommands_wizard_firstrunonly(self): return True @@ -42,7 +38,7 @@ class ServerCommandsSubwizard(object): # noinspection PyUnresolvedReferences,PyMethodMayBeStatic -class WebcamSubwizard(object): +class WebcamSubwizard: def _is_webcam_wizard_firstrunonly(self): return True @@ -61,7 +57,7 @@ class WebcamSubwizard(object): # noinspection PyUnresolvedReferences,PyMethodMayBeStatic -class AclSubwizard(object): +class AclSubwizard: def _is_acl_wizard_firstrunonly(self): return False @@ -113,7 +109,7 @@ class AclSubwizard(object): # noinspection PyUnresolvedReferences,PyMethodMayBeStatic -class OnlineCheckSubwizard(object): +class OnlineCheckSubwizard: def _is_onlinecheck_wizard_firstrunonly(self): return False @@ -131,7 +127,7 @@ class OnlineCheckSubwizard(object): # noinspection PyUnresolvedReferences,PyMethodMayBeStatic -class PluginBlacklistSubwizard(object): +class PluginBlacklistSubwizard: def _is_pluginblacklist_wizard_firstrunonly(self): return False @@ -149,7 +145,7 @@ class PluginBlacklistSubwizard(object): # noinspection PyUnresolvedReferences,PyMethodMayBeStatic -class PrinterProfileSubwizard(object): +class PrinterProfileSubwizard: def _is_printerprofile_wizard_firstrunonly(self): return True @@ -167,7 +163,7 @@ class PrinterProfileSubwizard(object): Subwizards = type( - to_native_str("Subwizards"), + "Subwizards", tuple( cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 8c3a32b5e..f07882df3 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -12,27 +9,19 @@ For a spec see http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0. """ # 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 +import flask +import zeroconf +from flask_babel import gettext + +import octoprint.plugin +import octoprint.util + def __plugin_load__(): plugin = DiscoveryPlugin() @@ -197,20 +186,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 f"{name}.{service_type}" def _format_zeroconf_txt(self, record): result = {} @@ -251,15 +235,15 @@ class DiscoveryPlugin( name, addresses=addresses, port=port, - server="{}.local.".format(socket.gethostname()), + server=f"{socket.gethostname()}.local.", properties=txt_record, ) self._zeroconf.register_service(info, allow_name_change=True) self._zeroconf_registrations[key].append(info) - self._logger.info("Registered '{}' for {}".format(name, reg_type)) + self._logger.info(f"Registered '{name}' for {reg_type}") except Exception: self._logger.exception( - "Could not register {} for {} on port {}".format(name, reg_type, port) + f"Could not register {name} for {reg_type} on port {port}" ) def zeroconf_unregister(self, reg_type, port=None): @@ -283,10 +267,10 @@ class DiscoveryPlugin( try: for info in infos: self._zeroconf.unregister_service(info) - self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) + self._logger.debug(f"Unregistered {reg_type} on port {port}") except Exception: self._logger.exception( - "Could not (fully) unregister {} on port {}".format(reg_type, port) + f"Could not (fully) unregister {reg_type} on port {port}" ) def zeroconf_browse( @@ -337,7 +321,7 @@ class DiscoveryPlugin( result_available = threading.Event() result_available.clear() - class ZeroconfListener(object): + class ZeroconfListener: def __init__(self, logger): self._logger = logger @@ -372,9 +356,7 @@ class DiscoveryPlugin( for address in map(lambda x: socket.inet_ntoa(x), info.addresses): result.append(to_result(info, address)) - self._logger.debug( - "Browsing Zeroconf for {service_type}".format(service_type=service_type) - ) + self._logger.debug(f"Browsing Zeroconf for {service_type}") def browse(): listener = ZeroconfListener(self._logger) @@ -429,13 +411,7 @@ class DiscoveryPlugin( import io import threading - - try: - # noinspection PyCompatibility - from http.client import HTTPResponse # py3 - except ImportError: - # noinspection PyCompatibility - from httplib import HTTPResponse # py2 + from http.client import HTTPResponse class Response(HTTPResponse): def __init__(self, response_text): @@ -618,8 +594,7 @@ class DiscoveryPlugin( if ( alive - and self._ssdp_last_notify + self._ssdp_notify_timeout - > octoprint.util.monotonic_time() + and self._ssdp_last_notify + self._ssdp_notify_timeout > time.monotonic() ): # we just sent an alive, no need to send another one now return @@ -686,7 +661,7 @@ class DiscoveryPlugin( except Exception: pass - self._ssdp_last_notify = octoprint.util.monotonic_time() + self._ssdp_last_notify = time.monotonic() def _ssdp_monitor(self, timeout=5): """ @@ -696,13 +671,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) @@ -742,7 +711,7 @@ class DiscoveryPlugin( + socket.inet_aton("0.0.0.0"), ) - self._logger.info("Registered {} for SSDP".format(self.get_instance_name())) + self._logger.info(f"Registered {self.get_instance_name()} for SSDP") self._ssdp_notify(alive=True) @@ -764,7 +733,7 @@ class DiscoveryPlugin( interface_address = octoprint.util.address_for_client( *address, addresses=self._settings.get(["addresses"]), - interfaces=self._settings.get(["interfaces"]) + interfaces=self._settings.get(["interfaces"]), ) if not interface_address: continue @@ -808,9 +777,9 @@ class DiscoveryPlugin( def get_instance_name(self): name = self._settings.global_get(["appearance", "name"]) if name: - return 'OctoPrint instance "{}"'.format(name) + return f'OctoPrint instance "{name}"' else: - return "OctoPrint instance on {}".format(socket.gethostname()) + return f"OctoPrint instance on {socket.gethostname()}" def get_interface_addresses(self): addresses = self._settings.get(["addresses"]) @@ -836,4 +805,4 @@ __plugin_disabling_discouraged__ = gettext( "discoverable on the network via Bonjour and uPnP." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" diff --git a/src/octoprint/plugins/errortracking/__init__.py b/src/octoprint/plugins/errortracking/__init__.py index a165a7865..58a5abcbb 100644 --- a/src/octoprint/plugins/errortracking/__init__.py +++ b/src/octoprint/plugins/errortracking/__init__.py @@ -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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -253,5 +250,5 @@ def __plugin_enable__(): __plugin_name__ = "Error Tracking" __plugin_author__ = "Gina Häußge" __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = ErrorTrackingPlugin() diff --git a/src/octoprint/plugins/eventmanager/__init__.py b/src/octoprint/plugins/eventmanager/__init__.py index da8a54eac..667c783b3 100644 --- a/src/octoprint/plugins/eventmanager/__init__.py +++ b/src/octoprint/plugins/eventmanager/__init__.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - from flask_babel import gettext import octoprint.events @@ -55,7 +53,7 @@ class EventManagerPlugin( __plugin_name__ = gettext("Event Manager") -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_author__ = "jneilliii" __plugin_license__ = "AGPLv3" __plugin_description__ = gettext( diff --git a/src/octoprint/plugins/gcodeviewer/__init__.py b/src/octoprint/plugins/gcodeviewer/__init__.py index 7bc359016..d9e9b8960 100644 --- a/src/octoprint/plugins/gcodeviewer/__init__.py +++ b/src/octoprint/plugins/gcodeviewer/__init__.py @@ -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" @@ -78,7 +75,7 @@ __plugin_disabling_discouraged__ = gettext( "Without this plugin the GCode Viewer in OctoPrint will no longer be " "available." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = GcodeviewerPlugin() # __plugin_hooks__ = { # "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 748c07680..8fcf640d1 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -19,11 +16,6 @@ from octoprint.server.util.flask import no_firstrun_access, redirect_to_tornado from octoprint.settings import settings from octoprint.util import is_hidden_path, yaml -try: - from os import scandir -except ImportError: - from scandir import scandir - class LoggingPlugin( octoprint.plugin.AssetPlugin, @@ -144,7 +136,7 @@ class LoggingPlugin( def _getLogFiles(self): files = [] basedir = settings().getBaseFolder("logs", check_writable=False) - for entry in scandir(basedir): + for entry in os.scandir(basedir): if is_hidden_path(entry.path) or not entry.name.endswith(".log"): continue @@ -242,7 +234,7 @@ class LoggingPlugin( for logger, level in new_levels.items(): level = logging.getLevelName(level) - self._logger.info("Setting logger {} level to {}".format(logger, level)) + self._logger.info(f"Setting logger {logger} level to {level}") self._logger.manager.loggerDict[logger].setLevel(level) def _is_managed_logger(self, logger): @@ -281,7 +273,7 @@ __plugin_disabling_discouraged__ = gettext( "the web interface." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = LoggingPlugin() __plugin_hooks__ = { "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 0b2e21c0f..cd67f2320 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 copy -import io import logging import os import re @@ -24,7 +20,6 @@ import requests import sarge from flask import Response, abort, jsonify, request from flask_babel import gettext -from past.builtins import basestring import octoprint.plugin import octoprint.plugin.core @@ -38,7 +33,7 @@ from octoprint.server.util.flask import ( with_revalidation_checking, ) from octoprint.settings import valid_boolean_trues -from octoprint.util import TemporaryDirectory, deprecated, to_bytes, to_native_str +from octoprint.util import deprecated, to_bytes from octoprint.util.net import download_file from octoprint.util.pip import ( OUTPUT_SUCCESS, @@ -57,11 +52,6 @@ from octoprint.util.version import ( from . import exceptions -try: - from os import scandir -except ImportError: - from scandir import scandir - _DATA_FORMAT_VERSION = "v3" DEFAULT_PLUGIN_REPOSITORY = "https://plugins.octoprint.org/plugins.json" @@ -101,7 +91,7 @@ def map_repository_entry(entry): if ( "python" in entry["compatibility"] and entry["compatibility"]["python"] is not None - and isinstance(entry["compatibility"]["python"], basestring) + and isinstance(entry["compatibility"]["python"], str) ): result["is_compatible"]["python"] = is_python_compatible( entry["compatibility"]["python"] @@ -739,9 +729,9 @@ 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 f".{kind.extension}" in PluginManagerPlugin.ARCHIVE_EXTENSIONS return False def _is_pythonfile(self, path): @@ -750,13 +740,11 @@ class PluginManagerPlugin( import ast try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) return True except Exception as exc: - self._logger.exception( - "Could not parse {} as python file: {}".format(path, exc) - ) + self._logger.exception(f"Could not parse {path} as python file: {exc}") return False @@ -778,7 +766,7 @@ class PluginManagerPlugin( if url is not None: # fetch URL - folder = TemporaryDirectory() + folder = tempfile.TemporaryDirectory() path = download_file(url, folder.name) source = url source_type = "url" @@ -803,12 +791,12 @@ class PluginManagerPlugin( raise exceptions.InvalidPackageFormat() except requests.exceptions.HTTPError as e: - self._logger.error("Could not fetch plugin from server, got {}".format(e)) + self._logger.error(f"Could not fetch plugin from server, got {e}") result = { "result": False, "source": source, "source_type": source_type, - "reason": "Could not fetch plugin from server, got {}".format(e), + "reason": f"Could not fetch plugin from server, got {e}", } self._send_result_notification("install", result) @@ -881,12 +869,7 @@ class PluginManagerPlugin( self._send_result_notification("install", result) return result - try: - # Py3 - from urllib.parse import quote as url_quote - except ImportError: - # Py2 - from urllib import quote as url_quote + from urllib.parse import quote as url_quote path = os.path.abspath(path) if os.sep != "/": @@ -900,7 +883,7 @@ class PluginManagerPlugin( path_url = "file://" + url_quote(path) shell_quote = sarge.shell_quote - self._logger.info("Installing plugin from {}".format(source)) + self._logger.info(f"Installing plugin from {source}") pip_args = [ "--disable-pip-version-check", "install", @@ -927,7 +910,7 @@ class PluginManagerPlugin( ) force = True except Exception as e: - self._logger.exception("Could not install plugin from {}".format(source)) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -950,7 +933,7 @@ class PluginManagerPlugin( try: _, stdout, stderr = self._call_pip(pip_args) except Exception as e: - self._logger.exception("Could not install plugin from {}".format(source)) + self._logger.exception(f"Could not install plugin from {source}") self._logger.exception("Reason: {}".format(repr(e))) result = { "result": False, @@ -1113,7 +1096,7 @@ class PluginManagerPlugin( if name is None: name = os.path.basename(path) - self._logger.info("Installing single file plugin {} from {}".format(name, source)) + self._logger.info(f"Installing single file plugin {name} from {source}") all_plugins_before = self._plugin_manager.find_plugins(existing={}) @@ -1157,10 +1140,10 @@ class PluginManagerPlugin( # copy plugin try: - self._log_call("cp {} {}".format(path, destination)) + self._log_call(f"cp {path} {destination}") shutil.copy(path, destination) except Exception: - self._logger.exception("Installing plugin from {} failed".format(source)) + self._logger.exception(f"Installing plugin from {source} failed") result = { "result": False, "source": source, @@ -1286,22 +1269,16 @@ class PluginManagerPlugin( if os.path.isdir(full_path): # plugin is installed via a plugin folder, need to use rmtree to get rid of it - self._log_stdout( - "Deleting plugin from {folder}".format(folder=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") shutil.rmtree(full_path) elif os.path.isfile(full_path): - self._log_stdout( - "Deleting plugin from {file}".format(file=plugin.location) - ) + self._log_stdout(f"Deleting plugin from {plugin.location}") os.remove(full_path) if full_path.endswith(".py"): pyc_file = "{full_path}c".format(**locals()) if os.path.isfile(pyc_file): - self._log_stdout( - "Deleting plugin from {file}".format(file=pyc_file) - ) + self._log_stdout(f"Deleting plugin from {pyc_file}") os.remove(pyc_file) else: @@ -1335,9 +1312,7 @@ class PluginManagerPlugin( if plugin.enabled: self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem disabling plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem disabling plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1352,9 +1327,7 @@ class PluginManagerPlugin( if plugin.loaded: self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: - self._logger.exception( - "Problem unloading plugin {name}".format(name=plugin.key) - ) + self._logger.exception(f"Problem unloading plugin {plugin.key}") result = { "result": False, "uninstalled": True, @@ -1381,7 +1354,7 @@ class PluginManagerPlugin( "plugin": self._to_external_plugin(plugin), } self._send_result_notification("uninstall", result) - self._logger.info("Plugin {} uninstalled".format(plugin.key)) + self._logger.info(f"Plugin {plugin.key} uninstalled") self._cleanup_disabled(plugin.key) if cleanup: @@ -1396,13 +1369,13 @@ class PluginManagerPlugin( result_notifications=True, settings_save=True, ): - if isinstance(plugin, basestring): + if isinstance(plugin, str): key = result_value = plugin else: key = plugin.key result_value = self._to_external_plugin(plugin) - message = "Cleaning up plugin {}...".format(key) + message = f"Cleaning up plugin {key}..." self._logger.info(message) self._log_stdout(message) @@ -1416,7 +1389,7 @@ class PluginManagerPlugin( # delete plugin data folder result_data = True if not self._cleanup_data(key): - message = "Could not delete data folder of plugin {}".format(key) + message = f"Could not delete data folder of plugin {key}" self._logger.exception(message) self._log_stderr(message) result_data = False @@ -1490,7 +1463,7 @@ class PluginManagerPlugin( return True except Exception: self._logger.exception( - "Could not delete plugin data folder at {}".format(data_folder) + f"Could not delete plugin data folder at {data_folder}" ) return False else: @@ -1744,9 +1717,7 @@ class PluginManagerPlugin( try: import json - with io.open( - self._repository_cache_path, "rt", encoding="utf-8" - ) as f: + with open(self._repository_cache_path, encoding="utf-8") as f: repo_data = json.load(f) self._repository_mtime = mtime self._logger.info( @@ -1772,9 +1743,7 @@ class PluginManagerPlugin( try: r = requests.get(repository_url, timeout=30) r.raise_for_status() - self._logger.info( - "Loaded plugin repository data from {}".format(repository_url) - ) + self._logger.info(f"Loaded plugin repository data from {repository_url}") except Exception as e: self._logger.exception( "Could not fetch plugins from repository at {repository_url}: {message}".format( @@ -1786,13 +1755,13 @@ class PluginManagerPlugin( try: repo_data = r.json() except Exception as e: - self._logger.exception("Error while reading repository data: {}".format(e)) + self._logger.exception(f"Error while reading repository data: {e}") return None # validation if not isinstance(repo_data, (list, tuple)): self._logger.warning( - "Invalid repository data: expected a list, got {!r}".format(repo_data) + f"Invalid repository data: expected a list, got {repo_data!r}" ) return None @@ -1839,7 +1808,7 @@ class PluginManagerPlugin( try: import json - with io.open(self._notices_cache_path, "rt", encoding="utf-8") as f: + with open(self._notices_cache_path, encoding="utf-8") as f: notice_data = json.load(f) self._notices_mtime = mtime self._logger.info("Loaded notice data from disk, was still valid") @@ -1863,7 +1832,7 @@ class PluginManagerPlugin( try: r = requests.get(notices_url, timeout=30) r.raise_for_status() - self._logger.info("Loaded plugin notices data from {}".format(notices_url)) + self._logger.info(f"Loaded plugin notices data from {notices_url}") except Exception as e: self._logger.exception( "Could not fetch notices from {notices_url}: {message}".format( @@ -1946,7 +1915,7 @@ class PluginManagerPlugin( orphans[key]["settings"] = True # data - for entry in scandir(self._settings.getBaseFolder("data")): + for entry in os.scandir(self._settings.getBaseFolder("data")): if not entry.is_dir(): continue @@ -1973,9 +1942,7 @@ class PluginManagerPlugin( try: result = hook() if isinstance(result, (list, tuple)): - reconnect_hooks.extend( - filter(lambda x: isinstance(x, basestring), result) - ) + reconnect_hooks.extend(filter(lambda x: isinstance(x, str), result)) except Exception: self._logger.exception( "Error while retrieving additional hooks for which a " @@ -2148,7 +2115,7 @@ __plugin_author__ = "Gina Häußge" __plugin_url__ = "https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html" __plugin_description__ = "Allows installing and managing OctoPrint plugins" __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_hidden__ = True diff --git a/src/octoprint/plugins/pluginmanager/exceptions.py b/src/octoprint/plugins/pluginmanager/exceptions.py index 0b4256018..26a871dd0 100644 --- a/src/octoprint/plugins/pluginmanager/exceptions.py +++ b/src/octoprint/plugins/pluginmanager/exceptions.py @@ -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" diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 8a9b7db8d..63074d2f5 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import datetime __author__ = "Gina Häußge " @@ -33,7 +30,7 @@ from octoprint.server.util.flask import ( no_firstrun_access, with_revalidation_checking, ) -from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml +from octoprint.util import dict_merge, get_formatted_size, to_str, yaml from octoprint.util.pip import create_pip_caller from octoprint.util.version import ( get_comparable_version, @@ -389,9 +386,7 @@ class SoftwareUpdatePlugin( data = psutil.disk_usage(path) info["free"] = data.free except Exception: - self._logger.exception( - "Error while determining disk usage of {}".format(path) - ) + self._logger.exception(f"Error while determining disk usage of {path}") continue storage_info[key] = info @@ -427,15 +422,13 @@ class SoftwareUpdatePlugin( ) def _get_check_overlay(self, url): - self._logger.info("Fetching check overlays from {}".format(url)) + self._logger.info(f"Fetching check overlays from {url}") try: r = requests.get(url, timeout=3.1) r.raise_for_status() data = r.json() except Exception as exc: - self._logger.error( - "Could not fetch check overlay from {}: {}".format(url, exc) - ) + self._logger.error(f"Could not fetch check overlay from {url}: {exc}") return {} else: return data @@ -565,9 +558,7 @@ class SoftwareUpdatePlugin( ) cleaned_up = len(data) - before_cleanup if cleaned_up: - self._logger.info( - "Cleaned up {} old update log entries".format(cleaned_up) - ) + self._logger.info(f"Cleaned up {cleaned_up} old update log entries") with self._update_log_mutex: self._update_log = data @@ -1352,9 +1343,7 @@ class SoftwareUpdatePlugin( try: populated_check = self._populated_check(target, checks[target]) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") continue except Exception: self._logger.exception( @@ -1568,7 +1557,7 @@ class SoftwareUpdatePlugin( continue except Exception: self._logger.exception( - "Could not check {} for updates".format(target) + f"Could not check {target} for updates" ) continue @@ -1718,7 +1707,7 @@ class SoftwareUpdatePlugin( if isinstance(value, dict): lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) else: - lines.append("{!r}: {!r}".format(key, value)) + lines.append(f"{key!r}: {value!r}") return "{" + ", ".join(lines) + "}" @@ -1795,7 +1784,7 @@ class SoftwareUpdatePlugin( error = "unknown_check" except exceptions.NetworkError: self._logger.warning( - "Could not check {} for updates due to a network error".format(target) + f"Could not check {target} for updates due to a network error" ) update_possible = False error = "network" @@ -1809,12 +1798,12 @@ class SoftwareUpdatePlugin( error = "ratelimit" except exceptions.CheckError: self._logger.warning( - "Could not check {} for updates due to a check error".format(target) + f"Could not check {target} for updates due to a check error" ) update_possible = False error = "check" except Exception: - self._logger.exception("Could not check {} for updates".format(target)) + self._logger.exception(f"Could not check {target} for updates") update_possible = False error = "unknown" else: @@ -1824,9 +1813,7 @@ class SoftwareUpdatePlugin( target, check, online=online ) except Exception: - self._logger.exception( - "Error while checking if {} can be updated".format(target) - ) + self._logger.exception(f"Error while checking if {target} can be updated") update_possible = False self._version_cache[target] = { @@ -1866,9 +1853,7 @@ class SoftwareUpdatePlugin( try: populated_checks[target] = self._populated_check(target, check) except exceptions.UnknownCheckType: - self._logger.debug( - "Ignoring unknown check type for target {}".format(target) - ) + self._logger.debug(f"Ignoring unknown check type for target {target}") except Exception: self._logger.exception( "Error while populating check prior to update for target {}".format( @@ -2058,9 +2043,7 @@ class SoftwareUpdatePlugin( ### The actual update procedure starts here... try: - self._logger.info( - "Starting update of {} to {}...".format(target, target_version) - ) + self._logger.info(f"Starting update of {target} to {target_version}...") self._send_client_message( "updating", { @@ -2082,9 +2065,7 @@ class SoftwareUpdatePlugin( force=force, ) target_result = ("success", update_result) - self._logger.info( - "Update of {} to {} successful!".format(target, target_version) - ) + self._logger.info(f"Update of {target} to {target_version} successful!") trigger_event(True) except exceptions.UnknownUpdateType: @@ -2195,10 +2176,10 @@ class SoftwareUpdatePlugin( util.execute(restart_command, evaluate_returncode=False, do_async=True) except exceptions.ScriptError as e: self._logger.exception( - "Error while restarting via command {}".format(restart_command) + f"Error while restarting via command {restart_command}" ) - self._logger.warning("Restart stdout:\n{}".format(e.stdout)) - self._logger.warning("Restart stderr:\n{}".format(e.stderr)) + self._logger.warning(f"Restart stdout:\n{e.stdout}") + self._logger.warning(f"Restart stderr:\n{e.stderr}") raise exceptions.RestartFailed() def _populated_check(self, target, check): @@ -2214,13 +2195,13 @@ class SoftwareUpdatePlugin( if displayName is None: # displayName missing or set to None displayName = gettext("OctoPrint") - result["displayName"] = to_unicode(displayName, errors="replace") + result["displayName"] = to_str(displayName, errors="replace") displayVersion = check.get("displayVersion") if displayVersion is None: # displayVersion missing or set to None displayVersion = "{octoprint_version}" - result["displayVersion"] = to_unicode(displayVersion, errors="replace") + result["displayVersion"] = to_str(displayVersion, errors="replace") result["released_version"] = is_released_octoprint_version() @@ -2236,7 +2217,7 @@ class SoftwareUpdatePlugin( if displayName is None: # displayName missing or set to None displayName = gettext("pip") - result["displayName"] = to_unicode(displayName, errors="replace") + result["displayName"] = to_str(displayName, errors="replace") displayVersion = check.get("displayVersion") if displayVersion is None: @@ -2244,7 +2225,7 @@ class SoftwareUpdatePlugin( distribution = pkg_resources.get_distribution("pip") if distribution: displayVersion = distribution.version - result["displayVersion"] = to_unicode(displayVersion, errors="replace") + result["displayVersion"] = to_str(displayVersion, errors="replace") result["pip_command"] = check.get( "pip_command", @@ -2252,12 +2233,12 @@ class SoftwareUpdatePlugin( ) else: - result["displayName"] = to_unicode(check.get("displayName"), errors="replace") + result["displayName"] = to_str(check.get("displayName"), errors="replace") if result["displayName"] is None: # displayName missing or None - result["displayName"] = to_unicode(target, errors="replace") + result["displayName"] = to_str(target, errors="replace") - result["displayVersion"] = to_unicode( + result["displayVersion"] = to_str( check.get("displayVersion", check.get("current")), errors="replace" ) if result["displayVersion"] is None: @@ -2327,7 +2308,7 @@ class SoftwareUpdatePlugin( data={"loglines": [{"line": line, "stream": stream} for line in lines]}, ) for line in lines: - self._console_logger.debug("{} {}".format(prefix, line)) + self._console_logger.debug(f"{prefix} {line}") def _send_client_message(self, message_type, data=None): self._plugin_manager.send_plugin_message( @@ -2440,7 +2421,7 @@ __plugin_disabling_discouraged__ = gettext( "your system at risk." ) __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" def __plugin_load__(): diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index e80ef51fa..4590f0b96 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -65,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() @@ -233,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): try: r.raise_for_status() except requests.exceptions.HTTPError as e: - click.echo("Could not get update information from server, got {}".format(e)) + click.echo(f"Could not get update information from server, got {e}") sys.exit(1) data = r.json() diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 7acc08b63..93fb909b7 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -32,7 +29,7 @@ class NetworkError(Exception): if self.message is not None: return self.message elif self.cause is not None: - return "NetworkError caused by {}".format(self.cause) + return f"NetworkError caused by {self.cause}" else: return "NetworkError" @@ -47,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 diff --git a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py index 5b638ee62..b9500eb2a 100644 --- a/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py +++ b/src/octoprint/plugins/softwareupdate/scripts/update-octoprint.py @@ -1,6 +1,4 @@ #!/bin/env python -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Haeussge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -12,8 +10,6 @@ import sys import time import traceback -from past.builtins import unicode - # default close_fds settings if sys.platform == "win32" and sys.version_info < (3, 7): CLOSE_FDS = False @@ -56,7 +52,7 @@ def _to_unicode(s_or_u, encoding="utf-8", errors="strict"): def _to_bytes(s_or_u, encoding="utf-8", errors="strict"): """Make sure ``s_or_u`` is a str.""" - if isinstance(s_or_u, unicode): + if isinstance(s_or_u, str): return s_or_u.encode(encoding, errors=errors) else: return s_or_u @@ -96,14 +92,12 @@ def _execute(command, **kwargs): if not p.commands[0].process: # the process might have been set to None in case of any exception print( - "Error while trying to run command {}".format(joined_command), + f"Error while trying to run command {joined_command}", file=sys.stderr, ) return None, [], [] except Exception: - print( - "Error while trying to run command {}".format(joined_command), file=sys.stderr - ) + print(f"Error while trying to run command {joined_command}", file=sys.stderr) traceback.print_exc(file=sys.stderr) return None, [], [] @@ -158,7 +152,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 @@ -205,7 +199,7 @@ def _to_error(*lines): if len(lines) == 1: if isinstance(lines[0], (list, tuple)): lines = lines[0] - elif not isinstance(lines[0], (str, unicode)): + elif not isinstance(lines[0], (str, bytes)): lines = [ repr(lines[0]), ] @@ -219,7 +213,7 @@ def _rescue_changes(git_executable, folder): ) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git diff" failed with returncode {}'.format(returncode) + f'Could not update, "git diff" failed with returncode {returncode}' ) if stdout and "".join(stdout).strip(): # we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch @@ -227,9 +221,9 @@ def _rescue_changes(git_executable, folder): import time timestamp = time.strftime("%Y%m%d%H%M") - patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp)) + patch = os.path.join(folder, f"{timestamp}-preupdate.patch") - print(">>> Running: git diff and saving output to {}".format(patch)) + print(f">>> Running: git diff and saving output to {patch}") returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( @@ -238,9 +232,7 @@ def _rescue_changes(git_executable, folder): ) ) - import io - - with io.open(patch, "wt", encoding="utf-8", errors="replace") as f: + with open(patch, "wt", encoding="utf-8", errors="replace") as f: for line in stdout: f.write(line) @@ -279,11 +271,11 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git fetch" failed with returncode {}'.format(returncode) + f'Could not update, "git fetch" failed with returncode {returncode}' ) if branch is not None and branch.strip() != "": - print(">>> Running: git checkout {}".format(branch)) + print(f">>> Running: git checkout {branch}") returncode, stdout, stderr = _git( ["checkout", branch], folder, git_executable=git_executable ) @@ -298,7 +290,7 @@ def update_source(git_executable, folder, target, force=False, branch=None): returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable) if returncode is None or returncode != 0: raise RuntimeError( - 'Could not update, "git pull" failed with returncode {}'.format(returncode) + f'Could not update, "git pull" failed with returncode {returncode}' ) if force: @@ -321,7 +313,7 @@ def install_source(python_executable, folder, user=False, sudo=False): print(">>> Running: python setup.py clean") returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable) if returncode is None or returncode != 0: - print('"python setup.py clean" failed with returncode {}'.format(returncode)) + print(f'"python setup.py clean" failed with returncode {returncode}') print("Continuing anyways") print(">>> Running: python setup.py install") @@ -412,7 +404,7 @@ def main(): if python_executable.endswith('"'): python_executable = python_executable[:-1] - print("Python executable: {!r}".format(python_executable)) + print(f"Python executable: {python_executable!r}") folder = args.folder diff --git a/src/octoprint/plugins/softwareupdate/updaters/__init__.py b/src/octoprint/plugins/softwareupdate/updaters/__init__.py index 3a9fc471a..76c4cde58 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/__init__.py +++ b/src/octoprint/plugins/softwareupdate/updaters/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py index 33ef04a09..30df08b6b 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/pip.py +++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -101,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc target_version=target_version, target=target_version ) - logger.debug("Target: {}, executing pip install {}".format(target, install_arg)) + logger.debug(f"Target: {target}, executing pip install {install_arg}") pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"] pip_kwargs = { "env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"} diff --git a/src/octoprint/plugins/softwareupdate/updaters/python_updater.py b/src/octoprint/plugins/softwareupdate/updaters/python_updater.py index f552ee2ef..e2c8bcb47 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/python_updater.py +++ b/src/octoprint/plugins/softwareupdate/updaters/python_updater.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py index 776b891f1..00daef57a 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py +++ b/src/octoprint/plugins/softwareupdate/updaters/single_file_plugin.py @@ -1,17 +1,13 @@ -# -*- 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" import ast -import io import logging import os import shutil +import tempfile from octoprint.settings import settings -from octoprint.util import TemporaryDirectory from octoprint.util.net import download_file from .. import exceptions @@ -49,8 +45,8 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc folder = None try: try: - _log_message("Download file from {}".format(url)) - folder = TemporaryDirectory() + _log_message(f"Download file from {url}") + folder = tempfile.TemporaryDirectory() path = download_file(url, folder.name) except Exception as exc: raise exceptions.NetworkError(cause=exc) @@ -58,29 +54,25 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc filename = os.path.basename(path) _, ext = os.path.splitext(filename) if ext not in (".py",): - raise exceptions.UpdateError( - "File is not a python file: {}".format(filename), None - ) + raise exceptions.UpdateError(f"File is not a python file: {filename}", None) try: - with io.open(path, "rb") as f: + with open(path, "rb") as f: ast.parse(f.read(), filename=path) except Exception: - logger.exception("Could not parse {} as python file".format(path), None) + logger.exception(f"Could not parse {path} as python file", None) raise exceptions.UpdateError( - "Could not parse {} as python file.".format(filename), None + f"Could not parse {filename} as python file.", None ) destination = os.path.join(settings().getBaseFolder("plugins"), filename) try: - _log_message("Copy {} to {}".format(path, destination)) + _log_message(f"Copy {path} to {destination}") shutil.copy(path, destination) except Exception: - logger.exception("Could not copy {} to {}".format(path, destination)) - raise exceptions.UpdateError( - "Could not copy {} to {}".format(path, destination), None - ) + logger.exception(f"Could not copy {path} to {destination}") + raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None) return "ok" finally: diff --git a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py index 7ea45cc6a..7f1a4bea7 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py +++ b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py @@ -1,14 +1,9 @@ -# -*- 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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" import time -from octoprint.util import monotonic_time - def can_perform_update(target, check, online=True): return True @@ -17,9 +12,9 @@ def can_perform_update(target, check, online=True): def perform_update(target, check, target_version, log_cb=None, online=True, force=False): duration = check.get("duration", 30) - now = monotonic_time() + now = time.monotonic() end = now + duration while now < end: log_cb(["{}s left...".format(end - now)], prefix=">", stream="output") time.sleep(5) - now = monotonic_time() + now = time.monotonic() diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py index b7e115c6f..a50597688 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py +++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -81,9 +78,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc ### pre update if pre_update_script is not None: - logger.debug( - "Target: {}, running pre-update script: {}".format(target, pre_update_script) - ) + logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}") try: caller.checked_call(pre_update_script, cwd=folder) except CommandlineError as e: @@ -103,9 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc force="true" if force_exact_version else "false", ) - logger.debug( - "Target {}, running update script: {}".format(target, update_command) - ) + logger.debug(f"Target {target}, running update script: {update_command}") caller.checked_call(update_command, cwd=folder) except CommandlineError as e: diff --git a/src/octoprint/plugins/softwareupdate/util.py b/src/octoprint/plugins/softwareupdate/util.py index dbd6b1be5..f9b2a2922 100644 --- a/src/octoprint/plugins/softwareupdate/util.py +++ b/src/octoprint/plugins/softwareupdate/util.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -30,9 +27,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs): async_=do_async, ) except Exception: - logging.getLogger(__name__).exception( - "Error while executing command: {}".format(command) - ) + logging.getLogger(__name__).exception(f"Error while executing command: {command}") returncode = p.returncode if p is not None else None stdout = p.stdout.text if p is not None and p.stdout is not None else "" stderr = p.stderr.text if p is not None and p.stderr is not None else "" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py index 89d183c8b..737fbe3ce 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/__init__.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -24,12 +21,10 @@ from . import ( # noqa: F401 class GithubRateLimitCheckError(RateLimitCheckError): def __init__(self, remaining, ratelimit, reset): if reset: - message = "Github rate limit exceeded, reset at {}".format(reset) + message = f"Github rate limit exceeded, reset at {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): diff --git a/src/octoprint/plugins/softwareupdate/version_checks/always_current.py b/src/octoprint/plugins/softwareupdate/version_checks/always_current.py index 89cbe0505..2d46b3aed 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/always_current.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/always_current.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py index f94086742..45a51d824 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py @@ -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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -27,7 +24,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None): auth_value = base64.b64encode( b"{user}:{pw}".format(user=api_user, pw=api_password) ) - headers["authorization"] = "Basic {}".format(auth_value) + headers["authorization"] = f"Basic {auth_value}" try: r = requests.get(url, headers=headers, timeout=(3.05, 30)) @@ -82,19 +79,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, api_user, api_password ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py index f344cff2d..42ec5d963 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -59,8 +56,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.github_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_name, remote_name) - ) + logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py index 02135b7fd..1fa0e3591 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -33,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 @@ -100,8 +97,6 @@ def get_latest(target, check, online=True, *args, **kwargs): logger = logging.getLogger( "octoprint.plugins.softwareupdate.version_checks.git_commit" ) - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit) - ) + logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py index d20a28d20..551dd7d69 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -86,19 +83,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs): remote_commit = _get_latest_commit( check["user"], check["repo"], branch, apikey=apikey ) - remote_name = ( - "Commit {commit}".format(commit=remote_commit) - if remote_commit is not None - else "-" - ) + remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-" information["remote"] = {"name": remote_name, "value": remote_commit} is_current = ( current is not None and current == remote_commit ) or remote_commit is None - logger.debug( - "Target: {}, local: {}, remote: {}".format(target, current, remote_commit) - ) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}") return information, is_current diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py index 702c36308..c755bf639 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py @@ -1,8 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function - -# MO unicode_literals because fixing all the doctests is too annoying :-P - __author__ = "Gina Häußge " __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" @@ -203,7 +198,7 @@ def _get_comparable_version_semantic(version_string, force_base=True): version = semantic_version.Version.coerce(version_string, partial=False) if force_base: - version_string = "{}.{}.{}".format(version.major, version.minor, version.patch) + version_string = f"{version.major}.{version.minor}.{version.patch}" version = semantic_version.Version.coerce(version_string, partial=False) return version @@ -360,7 +355,7 @@ def get_latest( "release_notes": release_notes, } - logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag)) + logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}") return information, _is_current( information, compare_type, custom=custom_compare, force_base=force_base diff --git a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py index 4e277ff1a..0d1d48107 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/httpheader.py @@ -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" @@ -29,7 +26,7 @@ def get_latest(target, check, online=True, *args, **kwargs): method = check.get("header_method", "head") prefix = check.get("header_prefix", header) if prefix: - prefix = "{} ".format(prefix) + prefix = f"{prefix} " try: with requests.request(method, url) as r: diff --git a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py index eddfa6d2c..be724a984 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/jsondata.py @@ -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" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/never_current.py b/src/octoprint/plugins/softwareupdate/version_checks/never_current.py index d8fc2248d..0adddff08 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/never_current.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/never_current.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py b/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py index ae85b183d..5912f2f54 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/pypi_release.py @@ -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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -9,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, @@ -31,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()] diff --git a/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py b/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py index 6b6e5db36..c70212f7a 100644 --- a/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py +++ b/src/octoprint/plugins/softwareupdate/version_checks/python_checker.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 6b342fa13..9875fc55d 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -1,28 +1,19 @@ -# -*- 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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" +# noinspection PyCompatibility +import concurrent.futures import hashlib import logging +import time +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 import RepeatedTimer from octoprint.util.version import get_octoprint_version_string TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/" @@ -52,7 +43,7 @@ class TrackingPlugin( self._record_next_firmware_info = False - self._startup_time = monotonic_time() + self._startup_time = time.monotonic() def initialize(self): self._init_id() @@ -262,7 +253,7 @@ class TrackingPlugin( if not self._settings.get_boolean(["enabled"]): return - uptime = int(monotonic_time() - self._startup_time) + uptime = int(time.monotonic() - self._startup_time) printer_state = self._printer.get_state_id() self._track("ping", octoprint_uptime=uptime, printer_state=printer_state) @@ -523,7 +514,7 @@ class TrackingPlugin( # Don't print the URL or UUID! That would expose the UUID in forums/tickets # if pasted. It's okay for the user to know their uuid, but it shouldn't be shared. - headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())} + headers = {"User-Agent": f"OctoPrint/{get_octoprint_version_string()}"} try: params = urlencode(kwargs, doseq=True).replace("+", "%20") @@ -532,9 +523,7 @@ class TrackingPlugin( else: requests.get(url, params=params, timeout=3.1, headers=headers) - self._logger.info( - "Sent tracking event {}, payload: {!r}".format(event, kwargs) - ) + self._logger.info(f"Sent tracking event {event}, payload: {kwargs!r}") except Exception: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( @@ -576,6 +565,6 @@ __plugin_description__ = ( __plugin_url__ = "https://tracking.octoprint.org" __plugin_author__ = "Gina Häußge" __plugin_license__ = "AGPLv3" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" __plugin_implementation__ = TrackingPlugin() diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index 2808594ef..0dd5b1a45 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -137,7 +134,7 @@ __plugin_homepage__ = ( ) __plugin_license__ = "AGPLv3" __plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes" -__plugin_pythoncompat__ = ">=2.7,<4" +__plugin_pythoncompat__ = ">=3.7,<4" def __plugin_load__(): diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 6dad2982c..6a9362de1 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -1,47 +1,24 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" import collections -import io import json 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: - from scandir import scandir - -# noinspection PyCompatibility -from typing import Any - -from past.builtins import basestring from serial import SerialTimeoutException from octoprint.plugin import plugin_manager -from octoprint.util import ( - RepeatedTimer, - get_dos_filename, - monotonic_time, - to_bytes, - to_unicode, -) +from octoprint.util import RepeatedTimer, get_dos_filename, to_bytes, to_str # noinspection PyBroadException -class VirtualPrinter(object): +class VirtualPrinter: command_regex = re.compile(r"^([GMTF])(\d+)") sleep_regex = re.compile(r"sleep (\d+)") sleep_after_regex = re.compile(r"sleep_after ([GMTF]\d+) (\d+)") @@ -126,7 +103,7 @@ class VirtualPrinter(object): self.bedTargetTemp = 0.0 self.chamberTemp = self._ambient_temperature self.chamberTargetTemp = 0.0 - self.lastTempAt = monotonic_time() + self.lastTempAt = time.monotonic() self._relative = True self._lastX = 0.0 @@ -327,7 +304,7 @@ class VirtualPrinter(object): @timeout.setter def timeout(self, value): - self._logger.debug("Setting read timeout to {}s".format(value)) + self._logger.debug(f"Setting read timeout to {value}s") self._read_timeout = value @property @@ -336,7 +313,7 @@ class VirtualPrinter(object): @write_timeout.setter def write_timeout(self, value): - self._logger.debug("Setting write timeout to {}s".format(value)) + self._logger.debug(f"Setting write timeout to {value}s") self._write_timeout = value @property @@ -357,7 +334,7 @@ class VirtualPrinter(object): pass def _processIncoming(self): - next_wait_timeout = monotonic_time() + self._waitInterval + next_wait_timeout = time.monotonic() + self._waitInterval buf = b"" while self.incoming is not None and not self._killed: self._simulateTemps() @@ -371,9 +348,9 @@ class VirtualPrinter(object): data = to_bytes(data, encoding="ascii", errors="replace") self.incoming.task_done() except queue.Empty: - if self._sendWait and monotonic_time() > next_wait_timeout: + if self._sendWait and time.monotonic() > next_wait_timeout: self._send("wait") - next_wait_timeout = monotonic_time() + self._waitInterval + next_wait_timeout = time.monotonic() + self._waitInterval continue except Exception: if self.incoming is None: @@ -389,7 +366,7 @@ class VirtualPrinter(object): else: continue - next_wait_timeout = monotonic_time() + self._waitInterval + next_wait_timeout = time.monotonic() + self._waitInterval if data is None: continue @@ -468,7 +445,7 @@ class VirtualPrinter(object): if callable(prepared): prepared(linenumber, self.lastN, data) continue - elif isinstance(prepared, basestring): + elif isinstance(prepared, str): self._send(prepared) continue elif self._rerequest_last: @@ -480,7 +457,7 @@ class VirtualPrinter(object): data += b"\n" - data = to_unicode(data, encoding="ascii", errors="replace").strip() + data = to_str(data, encoding="ascii", errors="replace").strip() if data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG": debug_command = "" @@ -531,7 +508,7 @@ class VirtualPrinter(object): try: # if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first - letter_handler = "_gcode_{}".format(letter) + letter_handler = f"_gcode_{letter}" if hasattr(self, letter_handler): code = command_match.group(2) handled = getattr(self, letter_handler)(code, data) @@ -539,7 +516,7 @@ class VirtualPrinter(object): continue # then look for a method _gcode_ and execute that if it exists - command_handler = "_gcode_{}".format(command) + command_handler = f"_gcode_{command}" if hasattr(self, command_handler): handled = getattr(self, command_handler)(data) if handled: @@ -573,18 +550,16 @@ class VirtualPrinter(object): ##~~ command implementations # noinspection PyUnusedLocal - def _gcode_T(self, code, data): - # type: (str, str) -> None + def _gcode_T(self, code: str, data: str) -> None: t = int(code) if 0 <= t < self.extruderCount: self.currentExtruder = t self._send("Active Extruder: %d" % self.currentExtruder) else: - self._send("echo:T{} Invalid extruder ".format(t)) + self._send(f"echo:T{t} Invalid extruder ") # noinspection PyUnusedLocal - def _gcode_F(self, code, data): - # type: (str, str) -> bool + def _gcode_F(self, code: str, data: str) -> bool: if self._supportF: self._send("echo:changed F value") return False @@ -592,77 +567,64 @@ class VirtualPrinter(object): self._send(self._error("command_unknown", "F")) return True - def _gcode_M104(self, data): - # type: (str) -> None + def _gcode_M104(self, data: str) -> None: self._parseHotendCommand(data) - def _gcode_M109(self, data): - # type: (str) -> None + def _gcode_M109(self, data: str) -> None: self._parseHotendCommand(data, wait=True, support_r=True) - def _gcode_M140(self, data): - # type: (str) -> None + def _gcode_M140(self, data: str) -> None: self._parseBedCommand(data) - def _gcode_M190(self, data): - # type: (str) -> None + def _gcode_M190(self, data: str) -> None: self._parseBedCommand(data, wait=True, support_r=True) - def _gcode_M141(self, data): + def _gcode_M141(self, data: str) -> None: self._parseChamberCommand(data) - def _gcode_M191(self, data): + def _gcode_M191(self, data: str) -> None: self._parseChamberCommand(data, wait=True, support_r=True) # noinspection PyUnusedLocal - def _gcode_M105(self, data): - # type: (str) -> bool + def _gcode_M105(self, data: str) -> bool: self._processTemperatureQuery() return True # noinspection PyUnusedLocal - def _gcode_M20(self, data): - # type: (str) -> None + def _gcode_M20(self, data: str) -> None: if self._sdCardReady: self._listSd(incl_long="L" in data) # noinspection PyUnusedLocal - def _gcode_M21(self, data): - # type: (str) -> None + def _gcode_M21(self, data: str) -> None: self._sdCardReady = True self._send("SD card ok") # noinspection PyUnusedLocal - def _gcode_M22(self, data): - # type: (str) -> None + def _gcode_M22(self, data: str) -> None: self._sdCardReady = False - def _gcode_M23(self, data): - # type: (str) -> None + def _gcode_M23(self, data: str) -> None: if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._selectSdFile(filename) # noinspection PyUnusedLocal - def _gcode_M24(self, data): - # type: (str) -> None + def _gcode_M24(self, data: str) -> None: if self._sdCardReady: self._startSdPrint() # noinspection PyUnusedLocal - def _gcode_M25(self, data): - # type: (str) -> None + def _gcode_M25(self, data: str) -> None: if self._sdCardReady: self._pauseSdPrint() - def _gcode_M26(self, data): - # type: (str) -> None + def _gcode_M26(self, data: str) -> None: if self._sdCardReady: pos = int(re.search(r"S([0-9]+)", data).group(1)) self._setSdPos(pos) - def _gcode_M27(self, data): - # type: (str) -> None + def _gcode_M27(self, data: str) -> None: def report(): if self._sdCardReady: self._reportSdStatus() @@ -681,26 +643,22 @@ class VirtualPrinter(object): report() - def _gcode_M28(self, data): - # type: (str) -> None + def _gcode_M28(self, data: str) -> None: if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._writeSdFile(filename) # noinspection PyUnusedLocal - def _gcode_M29(self, data): - # type: (str) -> None + def _gcode_M29(self, data: str) -> None: if self._sdCardReady: self._finishSdFile() - def _gcode_M30(self, data): - # type: (str) -> None + def _gcode_M30(self, data: str) -> None: if self._sdCardReady: filename = data.split(None, 1)[1].strip() self._deleteSdFile(filename) - def _gcode_M33(self, data): - # type: (str) -> None + def _gcode_M33(self, data: str) -> None: if self._sdCardReady: filename = data.split(None, 1)[1].strip() if filename.startswith("/"): @@ -710,8 +668,7 @@ class VirtualPrinter(object): if file is not None: self._send(file["name"]) - def _gcode_M113(self, data): - # type: (str) -> None + def _gcode_M113(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) if matchS is not None: interval = int(matchS.group(1)) @@ -719,19 +676,17 @@ class VirtualPrinter(object): self._busyInterval = interval # noinspection PyUnusedLocal - def _gcode_M114(self, data): - # type: (str) -> bool + def _gcode_M114(self, data: str) -> bool: output = self._generatePositionOutput() if not self._okBeforeCommandOutput: ok = self._ok() if ok: - output = "{} {}".format(self._ok(), output) + output = f"{self._ok()} {output}" self._send(output) return True # noinspection PyUnusedLocal - def _gcode_M115(self, data): - # type: (str) -> None + def _gcode_M115(self, data: str) -> None: output = self._m115FormatString.format(firmware_name=self._firmwareName) self._send(output) @@ -739,8 +694,7 @@ class VirtualPrinter(object): for cap, enabled in self._capabilities.items(): self._send("Cap:{}:{}".format(cap.upper(), "1" if enabled else "0")) - def _gcode_M117(self, data): - # type: (str) -> None + def _gcode_M117(self, data: str) -> None: # we'll just use this to echo a message, to allow playing around with pause triggers if self._echoOnM117: try: @@ -748,8 +702,7 @@ class VirtualPrinter(object): except AttributeError: self._send("echo:") - def _gcode_M154(self, data): - # type: (str) -> None + def _gcode_M154(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) if matchS is not None: interval = int(matchS.group(1)) @@ -764,8 +717,7 @@ class VirtualPrinter(object): else: self._pos_reporter = None - def _gcode_M155(self, data): - # type: (str) -> None + def _gcode_M155(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) if matchS is not None: interval = int(matchS.group(1)) @@ -780,26 +732,22 @@ class VirtualPrinter(object): else: self._temperature_reporter = None - def _gcode_M220(self, data): - # type: (str) -> None + def _gcode_M220(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) if matchS is not None: self._feedrate_multiplier = float(matchS.group(1)) - def _gcode_M221(self, data): - # type: (str) -> None + def _gcode_M221(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) if matchS is not None: self._flowrate_multiplier = float(matchS.group(1)) # noinspection PyUnusedLocal - def _gcode_M400(self, data): - # type: (str) -> None + def _gcode_M400(self, data: str) -> None: self.buffered.join() # noinspection PyUnusedLocal - def _gcode_M600(self, data): - # type: (str) -> None + def _gcode_M600(self, data: str) -> None: self._send("//action:paused") self._showPrompt( "Heater Timeout", @@ -811,21 +759,18 @@ class VirtualPrinter(object): return True # handled as we don't want to send an ok now, only when finishing the busy # noinspection PyUnusedLocal - def _gcode_M876(self, data): - # type: (str) -> None + def _gcode_M876(self, data: str) -> None: self._hidePrompt() if self._busy == "paused for user": self._busy = None # noinspection PyUnusedLocal - def _gcode_M999(self, data): - # type: (str) -> None + def _gcode_M999(self, data: str) -> None: # mirror Marlin behaviour self._send("Resend: 1") # noinspection PyUnusedLocal - def _gcode_G20(self, data): - # type: (str) -> None + def _gcode_G20(self, data: str) -> None: self._unitModifier = 1 / 2.54 if self._lastX is not None: self._lastX *= 2.54 @@ -837,8 +782,7 @@ class VirtualPrinter(object): self._lastE = [e * 2.54 if e is not None else None for e in self._lastE] # noinspection PyUnusedLocal - def _gcode_G21(self, data): - # type: (str) -> None + def _gcode_G21(self, data: str) -> None: self._unitModifier = 1.0 if self._lastX is not None: self._lastX /= 2.54 @@ -850,25 +794,20 @@ class VirtualPrinter(object): self._lastE = [e / 2.54 if e is not None else None for e in self._lastE] # noinspection PyUnusedLocal - def _gcode_G90(self, data): - # type: (str) -> None + def _gcode_G90(self, data: str) -> None: self._relative = False # noinspection PyUnusedLocal - def _gcode_G91(self, data): - # type: (str) -> None + def _gcode_G91(self, data: str) -> None: self._relative = True - def _gcode_G92(self, data): - # type: (str) -> None + def _gcode_G92(self, data: str) -> None: self._setPosition(data) - def _gcode_G28(self, data): - # type: (str) -> None + def _gcode_G28(self, data: str) -> None: self._home(data) - def _gcode_G0(self, data): - # type: (str) -> None + def _gcode_G0(self, data: str) -> None: # simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves self.buffered.put(data) @@ -876,8 +815,7 @@ class VirtualPrinter(object): _gcode_G2 = _gcode_G0 _gcode_G3 = _gcode_G0 - def _gcode_G4(self, data): - # type: (str) -> None + def _gcode_G4(self, data: str) -> None: matchS = re.search(r"S([0-9]+)", data) matchP = re.search(r"P([0-9]+)", data) @@ -888,23 +826,22 @@ class VirtualPrinter(object): _timeout = float(matchS.group(1)) if self._sendBusy and self._busyInterval > 0: - until = monotonic_time() + _timeout - while monotonic_time() < until: + until = time.monotonic() + _timeout + while time.monotonic() < until: time.sleep(self._busyInterval) self._send("busy:processing") else: time.sleep(_timeout) # noinspection PyUnusedLocal - def _gcode_G33(self, data): - # type: (str) -> None + def _gcode_G33(self, data: str) -> None: self._send("G33 Auto Calibrate") self._send("Will take ~60s") timeout = 60 if self._sendBusy and self._busyInterval > 0: - until = monotonic_time() + timeout - while monotonic_time() < until: + until = time.monotonic() + timeout + while time.monotonic() < until: time.sleep(self._busyInterval) self._send("busy:processing") else: @@ -913,10 +850,10 @@ class VirtualPrinter(object): # Passcode Feature - lock with M510, unlock with M511 P. # https://marlinfw.org/docs/gcode/M510.html / https://marlinfw.org/docs/gcode/M511.html - def _gcode_M510(self, data): + def _gcode_M510(self, data: str) -> None: self._locked = True - def _gcode_M511(self, data): + def _gcode_M511(self, data: str) -> None: if self._locked: matchP = re.search(r"P([0-9]+)", data) if matchP: @@ -928,14 +865,14 @@ class VirtualPrinter(object): # EEPROM management commands - def _gcode_M500(self, data): + def _gcode_M500(self, data: str) -> None: # Stores settings to disk if self._virtual_eeprom: self._virtual_eeprom.save_settings() else: self._send(self._error("command_unknown", "M500")) - def _gcode_M501(self, data): + def _gcode_M501(self, data: str) -> None: # Read from EEPROM if self._virtual_eeprom: self._virtual_eeprom.read_settings() @@ -944,7 +881,7 @@ class VirtualPrinter(object): else: self._send(self._error("command_unknown", "M501")) - def _gcode_M502(self, data): + def _gcode_M502(self, data: str) -> None: # reset to default values if self._virtual_eeprom: self._virtual_eeprom.load_defaults() @@ -953,7 +890,7 @@ class VirtualPrinter(object): else: self._send(self._error("command_unknown", "M502")) - def _gcode_M503(self, data): + def _gcode_M503(self, data: str) -> None: # echo all eeprom data if self._virtual_eeprom and self._support_M503: for line in self._construct_eeprom_values(): @@ -961,7 +898,7 @@ class VirtualPrinter(object): else: self._send(self._error("command_unknown", "M503")) - def _gcode_M504(self, data): + def _gcode_M504(self, data: str) -> None: if self._virtual_eeprom: self._send("echo:EEPROM OK") else: @@ -969,7 +906,7 @@ class VirtualPrinter(object): # EEPROM settings commands - def _gcode_M92(self, data): + def _gcode_M92(self, data: str) -> None: # Steps per unit if not self._virtual_eeprom: self._send(self._error("command_unknown", "M92")) @@ -981,7 +918,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("XYZE", data).items(): self._virtual_eeprom.eeprom["steps"]["params"][key] = float(value) - def _gcode_M203(self, data): + def _gcode_M203(self, data: str) -> None: # Maximum feedrates (units/s) if not self._virtual_eeprom: self._send(self._error("command_unknown", "M203")) @@ -993,7 +930,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("XYZE", data).items(): self._virtual_eeprom.eeprom["feedrate"]["params"][key] = float(value) - def _gcode_M201(self, data): + def _gcode_M201(self, data: str) -> None: # Maximum Acceleration (units/s2) if not self._virtual_eeprom: self._send(self._error("command_unknown", "M201")) @@ -1005,7 +942,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("EXYZ", data).items(): self._virtual_eeprom.eeprom["max_accel"]["params"][key] = float(value) - def _gcode_M204(self, data): + def _gcode_M204(self, data: str) -> None: # Starting Acceleration (units/s2) if not self._virtual_eeprom: self._send(self._error("command_unknown", "M204")) @@ -1017,7 +954,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("PRTS", data).items(): self._virtual_eeprom.eeprom["start_accel"]["params"][key] = float(value) - def _gcode_M206(self, data): + def _gcode_M206(self, data: str) -> None: # Home offset if not self._virtual_eeprom: self._send(self._error("command_unknown", "M206")) @@ -1029,7 +966,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("XYZ", data).items(): self._virtual_eeprom.eeprom["home_offset"]["params"][key] = float(value) - def _gcode_M851(self, data): + def _gcode_M851(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M851")) return @@ -1039,7 +976,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("XYZ", data).items(): self._virtual_eeprom.eeprom["probe_offset"]["params"][key] = float(value) - def _gcode_M200(self, data): + def _gcode_M200(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M200")) return @@ -1049,7 +986,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("DS", data).items(): self._virtual_eeprom.eeprom["filament"]["params"][key] = float(value) - def _gcode_M666(self, data): + def _gcode_M666(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M666")) return @@ -1059,7 +996,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("XYZ", data).items(): self._virtual_eeprom.eeprom["endstop"]["params"][key] = float(value) - def _gcode_M665(self, data): + def _gcode_M665(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M665")) return @@ -1069,7 +1006,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("BHLRSXYZ", data).items(): self._virtual_eeprom.eeprom["delta"]["params"][key] = float(value) - def _gcode_M420(self, data): + def _gcode_M420(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M420")) return @@ -1079,7 +1016,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("SZ", data).items(): self._virtual_eeprom.eeprom["auto_level"]["params"][key] = float(value) - def _gcode_M900(self, data): + def _gcode_M900(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M900")) return @@ -1091,7 +1028,7 @@ class VirtualPrinter(object): value ) - def _gcode_M205(self, data): + def _gcode_M205(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M205")) return @@ -1101,7 +1038,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("BSTXYZEJ", data).items(): self._virtual_eeprom.eeprom["advanced"]["params"][key] = float(value) - def _gcode_M145(self, data): + def _gcode_M145(self, data: str) -> None: # M145 is a bit special, since it refers to 2 sets of values under the same params if not self._virtual_eeprom: self._send(self._error("command_unknown", "M145")) @@ -1128,7 +1065,7 @@ class VirtualPrinter(object): key ] = float(value) - def _gcode_M301(self, data): + def _gcode_M301(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M301")) return @@ -1138,7 +1075,7 @@ class VirtualPrinter(object): for key, value in self._parse_eeprom_params("PID", data).items(): self._virtual_eeprom.eeprom["pid"]["params"][key] = float(value) - def _gcode_M304(self, data): + def _gcode_M304(self, data: str) -> None: if not self._virtual_eeprom: self._send(self._error("command_unknown", "M304")) return @@ -1177,7 +1114,7 @@ class VirtualPrinter(object): return lines @staticmethod - def _parse_eeprom_params(letters, line): + def _parse_eeprom_params(letters: str, line: str) -> dict: # letters provided in a string (eg "XYZ") and line (eg. M92 X20 Y20 Z20) # are parsed into a dict params = list(letters) @@ -1207,8 +1144,7 @@ class VirtualPrinter(object): ##~~ further helpers # noinspection PyMethodMayBeStatic - def _calculate_checksum(self, line): - # type: (bytes) -> int + def _calculate_checksum(self, line: bytes) -> int: checksum = 0 for c in bytearray(line): checksum ^= c @@ -1220,8 +1156,9 @@ class VirtualPrinter(object): self._killed = True self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.") - def _triggerResend(self, expected=None, actual=None, checksum=None): - # type: (int, int, int) -> None + def _triggerResend( + self, expected: int = None, actual: int = None, checksum: int = None + ) -> None: with self._incoming_lock: if expected is None: expected = self.lastN + 1 @@ -1243,8 +1180,7 @@ class VirtualPrinter(object): request_resend() - def _debugTrigger(self, data): - # type: (str) -> None + def _debugTrigger(self, data: str) -> None: if data == "" or data == "help" or data == "?": usage = """ OctoPrint Virtual Printer debug commands @@ -1327,7 +1263,7 @@ class VirtualPrinter(object): | Unsets the busy loop. """ for line in usage.split("\n"): - self._send("echo: {}".format(line.strip())) + self._send(f"echo: {line.strip()}") elif data == "action_pause": self._send("// action:pause") elif data == "action_resume": @@ -1399,9 +1335,7 @@ class VirtualPrinter(object): if sleep_match is not None: interval = int(sleep_match.group(1)) - self._send( - "// sleeping for {interval} seconds".format(interval=interval) - ) + self._send(f"// sleeping for {interval} seconds") self._debug_sleep = interval elif sleep_after_match is not None: command = sleep_after_match.group(1) @@ -1470,10 +1404,9 @@ class VirtualPrinter(object): self._send(item) self._send("End file list") - def _mappedSdList(self): - # type: () -> collections.OrderedDict + def _mappedSdList(self) -> collections.OrderedDict: result = collections.OrderedDict() - for entry in scandir(self._virtualSd): + for entry in os.scandir(self._virtualSd): if not entry.is_file(): continue dosname = get_dos_filename( @@ -1489,8 +1422,7 @@ class VirtualPrinter(object): } return result - def _selectSdFile(self, filename, check_already_open=False): - # type: (str, bool) -> None + def _selectSdFile(self, filename: str, check_already_open: bool = False) -> None: if filename.startswith("/"): filename = filename[1:] @@ -1538,8 +1470,7 @@ class VirtualPrinter(object): else: self._send("Not SD printing") - def _generatePositionOutput(self): - # type: () -> str + def _generatePositionOutput(self) -> str: m114FormatString = self._settings.get(["m114FormatString"]) e = {index: value for index, value in enumerate(self._lastE)} e["current"] = self._lastE[self.currentExtruder] @@ -1561,8 +1492,7 @@ class VirtualPrinter(object): ) return output - def _generateTemperatureOutput(self): - # type: () -> str + def _generateTemperatureOutput(self) -> str: if self._settings.get_boolean(["repetierStyleTargetTemperature"]): template = self._settings.get(["m105NoTargetFormatString"]) else: @@ -1585,7 +1515,7 @@ class VirtualPrinter(object): ["smoothieTemperatureReporting"] ): continue - temps["T{}".format(i)] = (self.temp[i], self.targetTemp[i]) + temps[f"T{i}"] = (self.temp[i], self.targetTemp[i]) if self._settings.get_boolean(["hasBed"]): temps["B"] = (self.bedTemp, self.bedTargetTemp) @@ -1622,11 +1552,12 @@ class VirtualPrinter(object): if includeOk: ok = self._ok() if ok: - output = "{} {}".format(ok, output) + output = f"{ok} {output}" self._send(output) - def _parseHotendCommand(self, line, wait=False, support_r=False): - # type: (str, bool, bool) -> None + def _parseHotendCommand( + self, line: str, wait: bool = False, support_r: bool = False + ) -> None: only_wait_if_higher = True tool = 0 toolMatch = re.search(r"T([0-9]+)", line) @@ -1651,8 +1582,7 @@ class VirtualPrinter(object): if self._settings.get_boolean(["repetierStyleTargetTemperature"]): self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool])) - def _parseBedCommand(self, line, wait=False, support_r=False): - # type: (str, bool, bool) -> None + def _parseBedCommand(self, line: str, wait: bool = False, support_r: bool = False): if not self._settings.get_boolean(["hasBed"]): return @@ -1690,8 +1620,7 @@ class VirtualPrinter(object): if wait: self._waitForHeatup("chamber", only_wait_if_higher) - def _performMove(self, line): - # type: (str) -> None + def _performMove(self, line: str) -> None: matchX = re.search(r"X(-?[0-9.]+)", line) matchY = re.search(r"Y(-?[0-9.]+)", line) matchZ = re.search(r"Z(-?[0-9.]+)", line) @@ -1792,8 +1721,7 @@ class VirtualPrinter(object): else: time.sleep(duration) - def _setPosition(self, line): - # type: (str) -> None + def _setPosition(self, line: str) -> None: matchX = re.search(r"X(-?[0-9.]+)", line) matchY = re.search(r"Y(-?[0-9.]+)", line) matchZ = re.search(r"Z(-?[0-9.]+)", line) @@ -1851,8 +1779,7 @@ class VirtualPrinter(object): if e: self._lastE = 0 - def _writeSdFile(self, filename): - # type: (str) -> None + def _writeSdFile(self, filename: str) -> None: filename = filename if filename.startswith("/"): filename = filename[1:] @@ -1865,7 +1792,7 @@ class VirtualPrinter(object): handle = None try: - handle = io.open(file, "wt", encoding="utf-8") + handle = open(file, "wt", encoding="utf-8") except Exception: self._send("error writing to file") self._writingToSdHandle = handle @@ -1887,7 +1814,7 @@ class VirtualPrinter(object): def _sdPrintingWorker(self): self._selectedSdFilePos = 0 try: - with io.open(self._selectedSdFile, "rt", encoding="utf-8") as f: + with open(self._selectedSdFile, encoding="utf-8") as f: for line in iter(f.readline, ""): if self._killed or not self._sdPrinting: break @@ -1933,11 +1860,10 @@ class VirtualPrinter(object): self._sdPrinting = False self._sdPrinter = None - def _waitForHeatup(self, heater, only_wait_if_higher): - # type: (str, bool) -> None + def _waitForHeatup(self, heater: str, only_wait_if_higher: bool) -> None: delta = 1 delay = 1 - last_busy = monotonic_time() + last_busy = time.monotonic() self._heatingUp = True try: @@ -1965,9 +1891,9 @@ class VirtualPrinter(object): while not self._killed and self._heatingUp and test(): self._simulateTemps(delta=delta) self._send(output()) - if self._sendBusy and monotonic_time() - last_busy >= self._busyInterval: + if self._sendBusy and time.monotonic() - last_busy >= self._busyInterval: self._send("echo:busy: processing") - last_busy = monotonic_time() + last_busy = time.monotonic() time.sleep(delay) except AttributeError: if self.outgoing is not None: @@ -1975,8 +1901,7 @@ class VirtualPrinter(object): finally: self._heatingUp = False - def _deleteSdFile(self, filename): - # type: (str) -> None + def _deleteSdFile(self, filename: str) -> None: if filename.startswith("/"): filename = filename[1:] files = self._mappedSdList() @@ -1989,8 +1914,8 @@ class VirtualPrinter(object): os.remove(file["path"]) def _simulateTemps(self, delta=0.5): - timeDiff = self.lastTempAt - monotonic_time() - self.lastTempAt = monotonic_time() + timeDiff = self.lastTempAt - time.monotonic() + self.lastTempAt = time.monotonic() def simulate(actual, target, ambient): if target > 0: @@ -2049,7 +1974,7 @@ class VirtualPrinter(object): def loop(): while self._busy: - self._send("echo:busy {}".format(self._busy)) + self._send(f"echo:busy {self._busy}") time.sleep(self._busyInterval) self._sendOk() @@ -2063,18 +1988,17 @@ class VirtualPrinter(object): def _showPrompt(self, text, choices): self._hidePrompt() - self._send("//action:prompt_begin {}".format(text)) + self._send(f"//action:prompt_begin {text}") for choice in choices: - self._send("//action:prompt_button {}".format(choice)) + self._send(f"//action:prompt_button {choice}") self._send("//action:prompt_show") def _hidePrompt(self): self._send("//action:prompt_end") - def write(self, data): - # type: (bytes) -> int + def write(self, data: bytes) -> int: data = to_bytes(data, errors="replace") - u_data = to_unicode(data, errors="replace") + u_data = to_str(data, errors="replace") if self._debug_awol: return len(data) @@ -2090,7 +2014,7 @@ class VirtualPrinter(object): return 0 if b"M112" in data and self._supportM112: - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") self._kill() return len(data) @@ -2098,7 +2022,7 @@ class VirtualPrinter(object): written = self.incoming.put( data, timeout=self._write_timeout, partial=True ) - self._seriallog.info("<<< {}".format(u_data)) + self._seriallog.info(f"<<< {u_data}") return written except queue.Full: self._logger.info( @@ -2106,8 +2030,7 @@ class VirtualPrinter(object): ) raise SerialTimeoutException() - def readline(self): - # type: () -> bytes + def readline(self) -> bytes: if self._debug_awol: time.sleep(self._read_timeout) return b"" @@ -2136,8 +2059,8 @@ class VirtualPrinter(object): try: # fetch a line from the queue, wait no longer than timeout - line = to_unicode(self.outgoing.get(timeout=timeout), errors="replace") - self._seriallog.info(">>> {}".format(line.strip())) + line = to_str(self.outgoing.get(timeout=timeout), errors="replace") + self._seriallog.info(f">>> {line.strip()}") self.outgoing.task_done() return to_bytes(line) except queue.Empty: @@ -2162,8 +2085,7 @@ class VirtualPrinter(object): if self.outgoing is not None: self._send("wait") - def _send(self, line): - # type: (str) -> None + def _send(self, line: str) -> None: if self.outgoing is not None: self.outgoing.put(line) @@ -2178,8 +2100,7 @@ class VirtualPrinter(object): ok, lastN=self.lastN, buffer=self.buffered.maxsize - self.buffered.qsize() ) - def _error(self, error, *args, **kwargs): - # type: (str, Any, Any) -> str + def _error(self, error: str, *args, **kwargs) -> str: return "Error: {}".format(self._errors.get(error).format(*args, **kwargs)) @@ -2192,14 +2113,14 @@ class VirtualEEPROM: def _initialise_eeprom(self): if os.path.exists(self._eeprom_file_path): # file exists, read it - with io.open(self._eeprom_file_path, "rt", encoding="utf-8") as eeprom_file: + with open(self._eeprom_file_path, encoding="utf-8") as eeprom_file: data = json.load(eeprom_file) return data else: # no eeprom file, make new one with defaults data = self.get_default_settings() - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: - eeprom_file.write(to_unicode(json.dumps(data))) + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + eeprom_file.write(to_str(json.dumps(data))) return data @staticmethod @@ -2309,15 +2230,15 @@ class VirtualEEPROM: def save_settings(self): # M500 behind-the-scenes - with io.open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: - eeprom_file.write(to_unicode(json.dumps(self._eeprom))) + with open(self._eeprom_file_path, "wt", encoding="utf-8") as eeprom_file: + eeprom_file.write(to_str(json.dumps(self._eeprom))) def read_settings(self): # M501 - if the file has disappeared, then recreate it if not os.path.exists(self._eeprom_file_path): self.load_defaults() self.save_settings() - with io.open(self._eeprom_file_path, "rt") as eeprom_file: + with open(self._eeprom_file_path) as eeprom_file: self._eeprom = json.load(eeprom_file) def load_defaults(self): @@ -2358,9 +2279,9 @@ class CharCountingQueue(queue.Queue): elif timeout < 0: raise ValueError("'timeout' must be a positive number") else: - endtime = monotonic_time() + timeout + endtime = time.monotonic() + timeout while not self._will_it_fit(item): - remaining = endtime - monotonic_time() + remaining = endtime - time.monotonic() if remaining <= 0: raise queue.Full self.not_full.wait(remaining) diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index d4e408b39..6b5d4d7c2 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module defines the interface for communicating with a connected printer. @@ -14,7 +13,6 @@ abstracted version of the actual printer communication. .. autoclass:: PrinterCallback :members: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -36,7 +34,7 @@ def get_connection_options(): return PrinterInterface.get_connection_options() -class PrinterInterface(object): +class PrinterInterface: """ The :class:`PrinterInterface` represents the developer interface to the :class:`~octoprint.printer.standard.Printer` instance. @@ -605,7 +603,7 @@ class PrinterInterface(object): raise NotImplementedError() -class PrinterCallback(object): +class PrinterCallback: def on_printer_add_log(self, data): """ Called when the :class:`PrinterInterface` receives a new communication log entry from the communication layer. diff --git a/src/octoprint/printer/estimation.py b/src/octoprint/printer/estimation.py index 29e530160..8aa16b135 100644 --- a/src/octoprint/printer/estimation.py +++ b/src/octoprint/printer/estimation.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,7 +6,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from octoprint.settings import settings -class PrintTimeEstimator(object): +class PrintTimeEstimator: """ Estimator implementation. @@ -199,7 +196,7 @@ class PrintTimeEstimator(object): return self._data.update(printTime / progress) -class TimeEstimationHelper(object): +class TimeEstimationHelper: STABLE_THRESHOLD = 0.1 STABLE_COUNTDOWN = 250 diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py index 03db920a7..5baafe6b6 100644 --- a/src/octoprint/printer/profile.py +++ b/src/octoprint/printer/profile.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module contains printer profile related code. @@ -139,7 +138,6 @@ A printer profile is a ``dict`` of the following structure: .. autoclass:: InvalidProfileError """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -150,11 +148,6 @@ import copy import logging import os -try: - from os import scandir -except ImportError: - from scandir import scandir - from octoprint.settings import settings from octoprint.util import ( dict_contains_keys, @@ -183,7 +176,7 @@ class InvalidProfileError(Exception): pass -class BedFormFactor(object): +class BedFormFactor: """Valid values for bed form factor""" RECTANGULAR = "rectangular" @@ -205,7 +198,7 @@ BedTypes = BedFormFactor """Deprecated name of :class:`BedFormFactors`""" -class BedOrigin(object): +class BedOrigin: """Valid values for bed origin""" LOWERLEFT = "lowerleft" @@ -223,7 +216,7 @@ class BedOrigin(object): ] -class PrinterProfileManager(object): +class PrinterProfileManager: """ Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove, load and save printer profiles. @@ -435,7 +428,7 @@ class PrinterProfileManager(object): dates = [os.stat(self._folder).st_mtime] dates += [ entry.stat().st_mtime - for entry in scandir(self._folder) + for entry in os.scandir(self._folder) if entry.name.endswith(".profile") ] return max(dates) @@ -486,7 +479,7 @@ class PrinterProfileManager(object): try: profile = self._load_from_path(path) except InvalidProfileError: - self._logger.warning("Profile {} is invalid, skipping".format(identifier)) + self._logger.warning(f"Profile {identifier} is invalid, skipping") continue if profile is None: @@ -497,7 +490,7 @@ class PrinterProfileManager(object): def _load_all_identifiers(self): results = {} - for entry in scandir(self._folder): + for entry in os.scandir(self._folder): if is_hidden_path(entry.name) or not entry.name.endswith(".profile"): continue diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index c7fccc8a0..baf33070b 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This module holds the standard implementation of the :class:`PrinterInterface` and it helpers. """ @@ -16,7 +13,6 @@ import threading import time from frozendict import frozendict -from past.builtins import basestring, long import octoprint.util.json from octoprint import util as util @@ -35,7 +31,7 @@ from octoprint.settings import settings from octoprint.util import InvariantContainer from octoprint.util import comm as comm from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import monotonic_time, to_unicode +from octoprint.util import to_str class Printer(PrinterInterface, comm.MachineComPrintCallback): @@ -48,7 +44,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): from collections import deque self._logger = logging.getLogger(__name__) - self._logger_job = logging.getLogger("{}.job".format(__name__)) + self._logger_job = logging.getLogger(f"{__name__}.job") self._dict = ( frozendict @@ -104,13 +100,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): try: estimator = hook() if estimator is not None: - self._logger.info( - "Using print time estimator provided by {}".format(name) - ) + self._logger.info(f"Using print time estimator provided by {name}") self._estimator_factory = estimator except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) @@ -281,7 +275,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): plugin_data[name] = additional except ValueError: self._logger.exception( - "Invalid additional data from plugin {}".format(name), + f"Invalid additional data from plugin {name}", extra={"plugin": name}, ) except Exception: @@ -362,13 +356,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if hook( self, port=port, baudrate=baudrate, profile=profile, *args, **kwargs ): - self._logger.info( - "Connect signalled as handled by plugin {}".format(name) - ) + self._logger.info(f"Connect signalled as handled by plugin {name}") return except Exception: self._logger.exception( - "Exception while handling connect in plugin {}".format(name), + f"Exception while handling connect in plugin {name}", extra={"plugin": name}, ) @@ -463,7 +455,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): # this code preserves existing CamelCase event_name = name[0].upper() + name[1:] - event_start = "GcodeScript{}Running".format(event_name) + event_start = f"GcodeScript{event_name}Running" payload = context.get("event", None) if isinstance(context, dict) else None eventManager().fire(event_start, payload) @@ -477,21 +469,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if not result and must_be_set: raise UnknownScript(name) - event_end = "GcodeScript{}Finished".format(event_name) + event_end = f"GcodeScript{event_name}Finished" eventManager().fire(event_end, payload) def jog(self, axes, relative=True, speed=None, *args, **kwargs): - if isinstance(axes, basestring): + if isinstance(axes, str): # legacy parameter format, there should be an amount as first anonymous positional arguments too axis = axes if not len(args) >= 1: raise ValueError("amount not set") amount = args[0] - if not isinstance(amount, (int, long, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + if not isinstance(amount, (int, float)): + raise ValueError(f"amount must be a valid number: {amount}") axes = {} axes[axis] = amount @@ -508,7 +498,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) command = "G0 {}".format( - " ".join(["{}{}".format(axis.upper(), amt) for axis, amt in axes.items()]) + " ".join([f"{axis.upper()}{amt}" for axis, amt in axes.items()]) ) if speed is None: @@ -516,7 +506,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) if speed and not isinstance(speed, bool): - command += " F{}".format(speed) + command += f" F{speed}" if relative: commands = ["G91", command, "G90"] @@ -527,12 +517,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def home(self, axes, *args, **kwargs): if not isinstance(axes, (list, tuple)): - if isinstance(axes, basestring): + if isinstance(axes, str): axes = [axes] else: - raise ValueError( - "axes is neither a list nor a string: {axes}".format(axes=axes) - ) + raise ValueError(f"axes is neither a list nor a string: {axes}") validated_axes = list( filter( @@ -540,7 +528,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) ) if len(axes) != len(validated_axes): - raise ValueError("axes contains invalid axes: {axes}".format(axes=axes)) + raise ValueError(f"axes contains invalid axes: {axes}") self.commands( [ @@ -552,10 +540,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) def extrude(self, amount, speed=None, *args, **kwargs): - if not isinstance(amount, (int, long, float)): - raise ValueError( - "amount must be a valid number: {amount}".format(amount=amount) - ) + if not isinstance(amount, (int, float)): + raise ValueError(f"amount must be a valid number: {amount}") printer_profile = self._printerProfileManager.get_current_or_default() @@ -576,7 +562,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def change_tool(self, tool, *args, **kwargs): if not PrinterInterface.valid_tool_regex.match(tool): - raise ValueError('tool must match "tool[0-9]+": {tool}'.format(tool=tool)) + raise ValueError(f'tool must match "tool[0-9]+": {tool}') tool_num = int(tool[len("tool") :]) self.commands( @@ -592,10 +578,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): ) ) - if not isinstance(value, (int, long, float)) or value < 0: - raise ValueError( - "value must be a valid number >= 0: {value}".format(value=value) - ) + if not isinstance(value, (int, float)) or value < 0: + raise ValueError(f"value must be a valid number >= 0: {value}") tags = kwargs.get("tags", set()) | {"trigger:printer.set_temperature"} @@ -605,15 +589,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): shared_nozzle = printer_profile["extruder"]["sharedNozzle"] if extruder_count > 1 and not shared_nozzle: toolNum = int(heater[len("tool") :]) - self.commands("M104 T{} S{}".format(toolNum, value), tags=tags) + self.commands(f"M104 T{toolNum} S{value}", tags=tags) else: - self.commands("M104 S{}".format(value), tags=tags) + self.commands(f"M104 S{value}", tags=tags) elif heater == "bed": - self.commands("M140 S{}".format(value), tags=tags) + self.commands(f"M140 S{value}", tags=tags) elif heater == "chamber": - self.commands("M141 S{}".format(value), tags=tags) + self.commands(f"M141 S{value}", tags=tags) def set_temperature_offset(self, offsets=None, *args, **kwargs): if offsets is None: @@ -626,17 +610,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): filter(lambda x: PrinterInterface.valid_heater_regex.match(x), offsets.keys()) ) validated_values = list( - filter(lambda x: isinstance(x, (int, long, float)), offsets.values()) + filter(lambda x: isinstance(x, (int, float)), offsets.values()) ) if len(validated_keys) != len(offsets): - raise ValueError( - "offsets contains invalid keys: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid keys: {offsets}") if len(validated_values) != len(offsets): - raise ValueError( - "offsets contains invalid values: {offsets}".format(offsets=offsets) - ) + raise ValueError(f"offsets contains invalid values: {offsets}") if self._comm is None: return @@ -645,16 +625,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): self._setOffsets(self._comm.getOffsets()) def _convert_rate_value(self, factor, min_val=None, max_val=None): - if not isinstance(factor, (int, float, long)): + if not isinstance(factor, (int, float)): raise ValueError("factor is not a number") if isinstance(factor, float): factor = int(factor * 100) if min_val and factor < min_val: - raise ValueError("factor must be a value >={}".format(min_val)) + raise ValueError(f"factor must be a value >={min_val}") elif max_val and factor > max_val: - raise ValueError("factor must be a value <={}".format(max_val)) + raise ValueError(f"factor must be a value <={max_val}") return factor @@ -995,7 +975,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): sd_upload_succeeded, sd_upload_failed, *args, - **kwargs + **kwargs, ) if result is not None: return result @@ -1187,7 +1167,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): printTimeLeft = int(printTimeLeft) except Exception: self._logger.exception( - "Error while estimating print time via {}".format(estimator) + f"Error while estimating print time via {estimator}" ) return self._dict( @@ -1236,9 +1216,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def _validateJob(self, filename, sd): if not valid_file_type(filename, type="machinecode"): - raise InvalidFileType( - "{} is not a machinecode file, cannot print".format(filename) - ) + raise InvalidFileType(f"{filename} is not a machinecode file, cannot print") if sd: return @@ -1442,7 +1420,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): """ Callback method for the comm object, called upon log output. """ - self._addLog(to_unicode(message, "utf-8", errors="replace")) + self._addLog(to_str(message, "utf-8", errors="replace")) def on_comm_temperature_update(self, tools, bed, chamber, custom=None): if custom is None: @@ -1537,7 +1515,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): Callback method for the comm object, called upon message exchanges via serial. Stores the message in the message buffer, truncates buffer to the last 300 lines. """ - self._addMessage(to_unicode(message, "utf-8", errors="replace")) + self._addMessage(to_str(message, "utf-8", errors="replace")) def on_comm_progress(self): """ @@ -1924,7 +1902,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): return result -class StateMonitor(object): +class StateMonitor: def __init__( self, interval=0.5, @@ -1958,7 +1936,7 @@ class StateMonitor(object): self._progress_lock = threading.Lock() self._resends_lock = threading.Lock() - self._last_update = monotonic_time() + self._last_update = time.monotonic() self._worker = threading.Thread(target=self._work) self._worker.daemon = True self._worker.start() @@ -2044,7 +2022,7 @@ class StateMonitor(object): while True: self._change_event.wait() - now = monotonic_time() + now = time.monotonic() delta = now - self._last_update additional_wait_time = self._interval - delta if additional_wait_time > 0: @@ -2053,7 +2031,7 @@ class StateMonitor(object): with self._state_lock: data = self.get_current_data() self._update_callback(data) - self._last_update = monotonic_time() + self._last_update = time.monotonic() self._change_event.clear() except Exception: logging.getLogger(__name__).exception( diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 6e153126e..067c75b7f 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -1,13 +1,10 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 atexit import base64 -import io +import functools import logging import logging.config import mimetypes @@ -15,8 +12,8 @@ import os import re import signal import sys +import time import uuid # noqa: F401 -from builtins import bytes, range from collections import OrderedDict, defaultdict from babel import Locale @@ -39,7 +36,6 @@ from flask_login import ( # noqa: F401 session_protected, user_logged_out, ) -from past.builtins import basestring, unicode from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from werkzeug.exceptions import HTTPException @@ -224,7 +220,7 @@ def unauthorized_user(): # ~~ startup code -class Server(object): +class Server: def __init__( self, settings=None, @@ -342,7 +338,6 @@ class Server(object): util.tornado.fix_websocket_check_origin() util.tornado.enable_per_message_deflate_extension() util.flask.fix_flask_jsonify() - util.watchdog.fix_scandir() self._setup_mimetypes() @@ -397,7 +392,7 @@ class Server(object): analysis_queue_factories.update(**additional_factories) except Exception: self._logger.exception( - "Error while processing analysis queues from {}".format(name), + f"Error while processing analysis queues from {name}", extra={"plugin": name}, ) analysisQueue = octoprint.filemanager.analysis.AnalysisQueue( @@ -504,7 +499,7 @@ class Server(object): groupManager = factory(components, self._settings) if groupManager is not None: self._logger.debug( - "Created group manager instance from factory {}".format(name) + f"Created group manager instance from factory {name}" ) break except Exception: @@ -538,7 +533,7 @@ class Server(object): userManager = factory(components, self._settings) if userManager is not None: self._logger.debug( - "Created user manager instance from factory {}".format(name) + f"Created user manager instance from factory {name}" ) break except Exception: @@ -569,13 +564,11 @@ class Server(object): try: printer = factory(components) if printer is not None: - self._logger.debug( - "Created printer instance from factory {}".format(name) - ) + self._logger.debug(f"Created printer instance from factory {name}") break except Exception: self._logger.exception( - "Error while creating printer instance from factory {}".format(name), + f"Error while creating printer instance from factory {name}", extra={"plugin": name}, ) else: @@ -954,7 +947,7 @@ class Server(object): for entry in result: if not isinstance(entry, tuple) or not len(entry) == 3: continue - if not isinstance(entry[0], basestring): + if not isinstance(entry[0], str): continue if not isinstance(entry[2], dict): continue @@ -1104,7 +1097,7 @@ class Server(object): connectionOptions = printer.__class__.get_connection_options() if port in connectionOptions["ports"] or port == "AUTO" or port is None: self._logger.info( - "Trying to connect to configured serial port {}".format(port) + f"Trying to connect to configured serial port {port}" ) printer.connect( port=port, @@ -1161,9 +1154,7 @@ class Server(object): if self._host == "::": if self._v6_only: # only v6 - self._logger.info( - "Listening on http://[::]:{port}".format(port=self._port) - ) + self._logger.info(f"Listening on http://[::]:{self._port}") else: # all v4 and v6 self._logger.info( @@ -1287,12 +1278,10 @@ class Server(object): self._settings.getBaseFolder("data"), "last_safe_mode" ) try: - with io.open(self_mode_file, "w+", encoding="utf-8") as f: + with open(self_mode_file, "w+", encoding="utf-8") as f: f.write(self_mode) except Exception as ex: - self._logger.warn( - "Could not write safe mode file {}: {}".format(self_mode_file, ex) - ) + self._logger.warn(f"Could not write safe mode file {self_mode_file}: {ex}") def _create_socket_connection(self, session): global printer, fileManager, analysisQueue, userManager, eventManager, connectivityChecker @@ -1349,7 +1338,7 @@ class Server(object): logger.info("Server heartbeat <3") interval = settings().getFloat(["server", "heartbeat"]) - logger.info("Starting server heartbeat, {}s interval".format(interval)) + logger.info(f"Starting server heartbeat, {interval}s interval") timer = octoprint.util.RepeatedTimer(interval, log_heartbeat) timer.start() @@ -1413,7 +1402,7 @@ class Server(object): g.locale = self._get_locale() # used for performance measurement - g.start_time = octoprint.util.monotonic_time() + g.start_time = time.monotonic() if self._debug and "perfprofile" in request.args: try: @@ -1439,9 +1428,9 @@ class Server(object): return make_response(output_html) if hasattr(g, "start_time"): - end_time = octoprint.util.monotonic_time() + end_time = time.monotonic() duration_ms = int((end_time - g.start_time) * 1000) - response.headers.add("Server-Timing", "app;dur={}".format(duration_ms)) + response.headers.add("Server-Timing", f"app;dur={duration_ms}") return response @@ -1464,7 +1453,7 @@ class Server(object): result.add(locale.language) if locale.territory: # if a territory is specified, add that too - result.add("{}_{}".format(locale.language, locale.territory)) + result.add(f"{locale.language}_{locale.territory}") return result @@ -1532,7 +1521,7 @@ class Server(object): tag += ' target="_blank" rel="noreferrer noopener"' content = match.group("content") - return "<{tag}>{content}".format(tag=tag, content=content) + return f"<{tag}>{content}" return html_link_regex.sub(repl, text) @@ -1703,7 +1692,7 @@ class Server(object): kwargs.update(additional_request_data) try: - start = octoprint.util.monotonic_time() + start = time.monotonic() if plugin: logger.info( "Preemptively caching {} (ui {}) for {!r}".format( @@ -1726,9 +1715,7 @@ class Server(object): app(builder.get_environ(), lambda *a, **kw: None) logger.info( - "... done in {:.2f}s".format( - octoprint.util.monotonic_time() - start - ) + "... done in {:.2f}s".format(time.monotonic() - start) ) except Exception: logger.exception( @@ -1789,61 +1776,93 @@ class Server(object): from octoprint.server.api import api from octoprint.server.util.flask import make_api_error - blueprints = OrderedDict() - blueprints["/api"] = api - json_errors = ["/api"] + blueprints = [api] + api_endpoints = ["/api"] + registrators = [functools.partial(app.register_blueprint, api, url_prefix="/api")] # also register any blueprints defined in BlueprintPlugins ( - blueprint_from_plugins, - api_prefixes_from_plugins, + blueprints_from_plugins, + api_endpoints_from_plugins, + registrators_from_plugins, ) = self._prepare_blueprint_plugins() - blueprints.update(blueprint_from_plugins) - json_errors += api_prefixes_from_plugins + blueprints += blueprints_from_plugins + api_endpoints += api_endpoints_from_plugins + registrators += registrators_from_plugins # and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves - blueprints.update(self._prepare_asset_plugins()) + (blueprints_from_assets, registrators_from_assets) = self._prepare_asset_plugins() + blueprints += blueprints_from_assets + registrators += registrators_from_assets # make sure all before/after_request hook results are attached as well - self._add_plugin_request_handlers_to_blueprints(*blueprints.values()) + self._add_plugin_request_handlers_to_blueprints(*blueprints) # register everything with the system - for url_prefix, blueprint in blueprints.items(): - app.register_blueprint(blueprint, url_prefix=url_prefix) + for registrator in registrators: + registrator() @app.errorhandler(HTTPException) def _handle_api_error(ex): - if any(map(lambda x: request.path.startswith(x), json_errors)): + if any(map(lambda x: request.path.startswith(x), api_endpoints)): return make_api_error(ex.description, ex.code) else: return ex def _prepare_blueprint_plugins(self): - blueprints = OrderedDict() - api_prefixes = [] + def register_plugin_blueprint(plugin, blueprint, url_prefix): + try: + app.register_blueprint( + blueprint, url_prefix=url_prefix, name_prefix="plugin" + ) + self._logger.debug( + f"Registered API of plugin {plugin} under URL prefix {url_prefix}" + ) + except Exception: + self._logger.exception( + f"Error while registering blueprint of plugin {plugin}, ignoring it", + extra={"plugin": plugin}, + ) + + blueprints = [] + api_endpoints = [] + registrators = [] blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.BlueprintPlugin ) for plugin in blueprint_plugins: - try: - blueprint, prefix = self._prepare_blueprint_plugin(plugin) - api_prefixes += map( - lambda x: prefix + x, plugin.get_blueprint_api_prefixes() - ) - blueprints[prefix] = blueprint - except Exception: - self._logger.exception( - "Error while registering blueprint of " - "plugin {}, ignoring it".format(plugin._identifier), - extra={"plugin": plugin._identifier}, - ) - continue + blueprint, prefix = self._prepare_blueprint_plugin(plugin) - return blueprints, api_prefixes + blueprints.append(blueprint) + api_endpoints += map( + lambda x: prefix + x, plugin.get_blueprint_api_prefixes() + ) + registrators.append( + functools.partial( + register_plugin_blueprint, plugin._identifier, blueprint, prefix + ) + ) + + return blueprints, api_endpoints, registrators def _prepare_asset_plugins(self): - blueprints = OrderedDict() + def register_asset_blueprint(plugin, blueprint, url_prefix): + try: + app.register_blueprint( + blueprint, url_prefix=url_prefix, name_prefix="plugin" + ) + self._logger.debug( + f"Registered assets of plugin {plugin} under URL prefix {url_prefix}" + ) + except Exception: + self._logger.exception( + f"Error while registering blueprint of plugin {plugin}, ignoring it", + extra={"plugin": plugin}, + ) + + blueprints = [] + registrators = [] asset_plugins = octoprint.plugin.plugin_manager().get_implementations( octoprint.plugin.AssetPlugin @@ -1851,18 +1870,16 @@ class Server(object): for plugin in asset_plugins: if isinstance(plugin, octoprint.plugin.BlueprintPlugin): continue - try: - blueprint, prefix = self._prepare_asset_plugin(plugin) - blueprints[prefix] = blueprint - except Exception: - self._logger.exception( - "Error while registering assets of plugin " - "{}, ignoring it".format(plugin._identifier), - extra={"plugin": plugin._identifier}, - ) - continue + blueprint, prefix = self._prepare_asset_plugin(plugin) - return blueprints + blueprints.append(blueprint) + registrators.append( + functools.partial( + register_asset_blueprint, plugin._identifier, blueprint, prefix + ) + ) + + return blueprints, registrators def _prepare_blueprint_plugin(self, plugin): name = plugin._identifier @@ -1877,34 +1894,14 @@ class Server(object): if plugin.is_blueprint_protected(): blueprint.before_request(requireLoginRequestHandler) - url_prefix = "/plugin/{name}".format(name=name) - app.register_blueprint(blueprint, url_prefix=url_prefix) - - if self._logger: - self._logger.debug( - "Registered API of plugin {name} under URL prefix {url_prefix}".format( - name=name, url_prefix=url_prefix - ) - ) - + url_prefix = f"/plugin/{name}" return blueprint, url_prefix def _prepare_asset_plugin(self, plugin): name = plugin._identifier - url_prefix = "/plugin/{name}".format(name=name) - blueprint = Blueprint( - "plugin." + name, name, static_folder=plugin.get_asset_folder() - ) - app.register_blueprint(blueprint, url_prefix=url_prefix) - - if self._logger: - self._logger.debug( - "Registered assets of plugin {name} under URL prefix {url_prefix}".format( - name=name, url_prefix=url_prefix - ) - ) - + url_prefix = f"/plugin/{name}" + blueprint = Blueprint(name, name, static_folder=plugin.get_asset_folder()) return blueprint, url_prefix def _add_plugin_request_handlers_to_blueprints(self, *blueprints): @@ -2238,7 +2235,7 @@ class Server(object): js_plugins_bundle = Bundle( *js_plugins.values(), output="webassets/packed_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_app_bundle = Bundle( @@ -2251,7 +2248,7 @@ class Server(object): js_client_core_bundle = Bundle( *clientjs_core, output="webassets/packed_client_core.js", - filters=",".join(js_filters) + filters=",".join(js_filters), ) if len(clientjs_plugins) == 0: @@ -2260,7 +2257,7 @@ class Server(object): js_client_plugins_bundle = Bundle( *clientjs_plugins.values(), output="webassets/packed_client_plugins.js", - filters=",".join(js_plugin_filters) + filters=",".join(js_plugin_filters), ) js_client_bundle = Bundle( @@ -2291,7 +2288,7 @@ class Server(object): css_core_bundle = Bundle( *css_core, output="webassets/packed_core.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) if len(css_plugins) == 0: @@ -2300,7 +2297,7 @@ class Server(object): css_plugins_bundle = Bundle( *css_plugins, output="webassets/packed_plugins.css", - filters=",".join(css_filters) + filters=",".join(css_filters), ) css_app_bundle = Bundle( @@ -2325,7 +2322,7 @@ class Server(object): less_core_bundle = Bundle( *less_core, output="webassets/packed_core.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) if len(less_plugins) == 0: @@ -2334,7 +2331,7 @@ class Server(object): less_plugins_bundle = Bundle( *less_plugins, output="webassets/packed_plugins.less", - filters=",".join(less_filters) + filters=",".join(less_filters), ) less_app_bundle = Bundle( @@ -2350,13 +2347,13 @@ class Server(object): assets.register("js_client_core", js_client_core_bundle) for plugin, bundle in clientjs_plugins.items(): # register our collected clientjs plugin bundles so that they are bound to the environment - assets.register("js_client_plugin_{}".format(plugin), bundle) + assets.register(f"js_client_plugin_{plugin}", bundle) assets.register("js_client_plugins", js_client_plugins_bundle) assets.register("js_client", js_client_bundle) assets.register("js_core", js_core_bundle) for plugin, bundle in js_plugins.items(): # register our collected plugin bundles so that they are bound to the environment - assets.register("js_plugin_{}".format(plugin), bundle) + assets.register(f"js_plugin_{plugin}", bundle) assets.register("js_plugins", js_plugins_bundle) assets.register("js_app", js_app_bundle) assets.register("css_libs", css_libs_bundle) @@ -2385,15 +2382,9 @@ class Server(object): 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 @@ -2417,7 +2408,7 @@ class Server(object): if content_type: self.send_header("Content-Type", content_type) self.end_headers() - if isinstance(data, unicode): + if isinstance(data, str): data = data.encode("utf-8") self.wfile.write(data) break @@ -2453,7 +2444,7 @@ class Server(object): if not os.path.isfile(path): return "" - with io.open(path, "rb") as f: + with open(path, "rb") as f: data = f.read() return data @@ -2508,9 +2499,7 @@ class Server(object): if host == "::": if self._v6_only: - self._logger.debug( - "Starting intermediary server on http://[::]:{port}".format(port=port) - ) + self._logger.debug(f"Starting intermediary server on http://[::]:{port}") else: self._logger.debug( "Starting intermediary server on http://0.0.0.0:{port} and http://[::]:{port}".format( @@ -2598,7 +2587,7 @@ class Server(object): return "{}: {}".format(plugin, definition["name"]) def permission_role(plugin, role): - return "plugin_{}_{}".format(plugin, role) + return f"plugin_{plugin}_{role}" def process_regular_permission(plugin_info, definition): permissions = [] @@ -2628,7 +2617,7 @@ class Server(object): plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ) setattr( octoprint.access.permissions.Permissions, @@ -2639,7 +2628,7 @@ class Server(object): plugin=plugin_info.key, dangerous=dangerous, default_groups=default_groups, - *roles_and_permissions + *roles_and_permissions, ), ) @@ -2687,7 +2676,7 @@ class Server(object): postponed.append((plugin_info, p)) except Exception: self._logger.exception( - "Error while creating permission instance/s from {}".format(name) + f"Error while creating permission instance/s from {name}" ) # final resolution passes @@ -2725,7 +2714,7 @@ class Server(object): pass_number += 1 -class LifecycleManager(object): +class LifecycleManager: def __init__(self, plugin_manager): self._plugin_manager = plugin_manager @@ -2757,7 +2746,7 @@ class LifecycleManager(object): lifecycle_callback(name, plugin) def add_callback(self, events, callback): - if isinstance(events, basestring): + if isinstance(events, str): events = [events] for event in events: @@ -2769,7 +2758,7 @@ class LifecycleManager(object): if callback in self._plugin_lifecycle_callbacks[event]: self._plugin_lifecycle_callbacks[event].remove(callback) else: - if isinstance(events, basestring): + if isinstance(events, str): events = [events] for event in events: diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index 056d68283..83b625e74 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -1,11 +1,7 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 from flask import ( @@ -121,7 +117,7 @@ def pluginData(name): raise except Exception: logging.getLogger(__name__).exception( - "Error calling SimpleApiPlugin {}".format(name), extra={"plugin": name} + f"Error calling SimpleApiPlugin {name}", extra={"plugin": name} ) return abort(500) @@ -163,7 +159,7 @@ def pluginCommand(name): raise except Exception: logging.getLogger(__name__).exception( - "Error while executing SimpleApiPlugin {}".format(name), + f"Error while executing SimpleApiPlugin {name}", extra={"plugin": name}, ) return abort(500) @@ -271,7 +267,7 @@ def apiVersion(): return jsonify( server=octoprint.server.VERSION, api=VERSION, - text="OctoPrint {}".format(octoprint.server.DISPLAY_VERSION), + text=f"OctoPrint {octoprint.server.DISPLAY_VERSION}", ) @@ -484,7 +480,7 @@ def _test_path(data): os.makedirs(path) except Exception: logging.getLogger(__name__).exception( - "Error while trying to create {}".format(path) + f"Error while trying to create {path}" ) return jsonify( path=path, @@ -517,12 +513,12 @@ def _test_path(data): if check_writable_dir and check_type == "dir": try: test_path = os.path.join(path, ".testballoon.txt") - with io.open(test_path, "wb") as f: + with open(test_path, "wb") as f: f.write(b"Test") os.remove(test_path) except Exception: logging.getLogger(__name__).exception( - "Error while testing if {} is really writable".format(path) + f"Error while testing if {path} is really writable" ) return jsonify( path=path, @@ -548,7 +544,7 @@ def _test_url(data): from octoprint import util as util - class StatusCodeRange(object): + class StatusCodeRange: def __init__(self, start=None, end=None): self.start = start self.end = end @@ -687,7 +683,7 @@ def _test_url(data): response_result["content"] = content except Exception: logging.getLogger(__name__).exception( - "Error while running a test {} request on {}".format(method, url) + f"Error while running a test {method} request on {url}" ) outcome = False diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py index f024dc6eb..a41badce9 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Marc Hannappel " __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" diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index ba8a2d18e..ed612cd63 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index b46034d98..35c8b4da9 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,6 +6,7 @@ import hashlib import logging import os import threading +from urllib.parse import quote as urlquote import psutil from flask import abort, jsonify, make_response, request, url_for @@ -37,11 +35,6 @@ from octoprint.server.util.flask import ( from octoprint.settings import settings, valid_boolean_trues from octoprint.util import sv, time_this -try: - from urllib.parse import quote as urlquote -except ImportError: - from urllib import quote as urlquote # noqa: F401 - # ~~ GCODE file handling _file_cache = {} @@ -210,7 +203,7 @@ def runFilesTest(): ), ): counter += 1 - suggestion = name + "_{}".format(counter) + ext + suggestion = f"{name}_{counter}{ext}" return jsonify(exists=True, suggestion=suggestion) else: return jsonify(exists=False) @@ -346,7 +339,7 @@ def _getFileList( ) with _file_cache_mutex: - cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) + cache_key = f"{origin}:{path}:{recursive}:{filter}" files, lastmodified = _file_cache.get(cache_key, ([], None)) # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 if ( @@ -1104,7 +1097,7 @@ def gcodeFileCommand(filename, target): with Permissions.FILES_UPLOAD.require(403): # Copy and move are only possible on local storage if target not in [FileDestinations.LOCAL]: - abort(400, description="Unsupported target for {}".format(command)) + abort(400, description=f"Unsupported target for {command}") if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename @@ -1143,9 +1136,7 @@ def gcodeFileCommand(filename, target): is_folder = fileManager.folder_exists(target, filename) if not (is_file or is_folder): - abort( - 400, description="Neither file nor folder, can't {}".format(command) - ) + abort(400, description=f"Neither file nor folder, can't {command}") if command == "copy": # destination already there? error... diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py index 1ba5c6f8d..4de446326 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index b3f6f1b5c..07156b5fd 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,14 +6,6 @@ import logging import os import tarfile import zipfile - -from octoprint.util import yaml - -try: - from os import scandir -except ImportError: - from scandir import scandir - from collections import defaultdict from flask import abort, jsonify, request @@ -27,6 +16,7 @@ from octoprint.plugin import plugin_manager from octoprint.server.api import api from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import settings +from octoprint.util import yaml @api.route("/languages", methods=["GET"]) @@ -41,7 +31,7 @@ def getInstalledLanguagePacks(): plugin_packs = defaultdict( lambda: {"identifier": None, "display": None, "languages": []} ) - for entry in scandir(translation_folder): + for entry in os.scandir(translation_folder): if not entry.is_dir(): continue @@ -72,7 +62,7 @@ def getInstalledLanguagePacks(): return meta if entry.name == "_plugins": - for plugin_entry in scandir(entry.path): + for plugin_entry in os.scandir(entry.path): if not plugin_entry.is_dir(): continue @@ -84,7 +74,7 @@ def getInstalledLanguagePacks(): plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name plugin_packs[plugin_entry.name]["display"] = plugin_info.name - for language_entry in scandir(plugin_entry.path): + for language_entry in os.scandir(plugin_entry.path): try: plugin_packs[plugin_entry.name]["languages"].append( load_meta(language_entry.path, language_entry.name) diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py index aa31caaae..b892df317 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -8,7 +5,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re from flask import Response, abort, jsonify, request -from past.builtins import basestring, long, unicode from octoprint.access.permissions import Permissions from octoprint.printer import UnknownScript @@ -94,7 +90,7 @@ def printerToolCommand(): ##~~ tool selection if command == "select": tool = data["tool"] - if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: + if not isinstance(tool, str) or re.match(validation_regex, tool) is None: abort(400, description="tool is invalid") printer.change_tool(tool, tags=tags) @@ -108,7 +104,7 @@ def printerToolCommand(): for tool, value in targets.items(): if re.match(validation_regex, tool) is None: abort(400, description="targets contains invalid tool") - if not isinstance(value, (int, long, float)): + if not isinstance(value, (int, float)): abort(400, description="targets contains invalid value") validated_values[tool] = value @@ -125,7 +121,7 @@ def printerToolCommand(): for tool, value in offsets.items(): if re.match(validation_regex, tool) is None: abort(400, description="offsets contains invalid tool") - if not isinstance(value, (int, long, float)) or not -50 <= value <= 50: + if not isinstance(value, (int, float)) or not -50 <= value <= 50: abort(400, description="offsets contains invalid value") validated_values[tool] = value @@ -140,13 +136,13 @@ def printerToolCommand(): amount = data["amount"] speed = data.get("speed", None) - if not isinstance(amount, (int, long, float)): + if not isinstance(amount, (int, float)): abort(400, description="amount is invalid") printer.extrude(amount, speed=speed, tags=tags) elif command == "flowrate": factor = data["factor"] - if not isinstance(factor, (int, long, float)): + if not isinstance(factor, (int, float)): abort(400, description="factor is invalid") try: printer.flow_rate(factor, tags=tags) @@ -191,7 +187,7 @@ def printerBedCommand(): target = data["target"] # make sure the target is a number - if not isinstance(target, (int, long, float)): + if not isinstance(target, (int, float)): abort(400, description="target is invalid") # perform the actual temperature command @@ -202,7 +198,7 @@ def printerBedCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: abort(400, description="offset is invalid") # set the offsets @@ -253,7 +249,7 @@ def printerChamberCommand(): target = data["target"] # make sure the target is a number - if not isinstance(target, (int, long, float)): + if not isinstance(target, (int, float)): abort(400, description="target is invalid") # perform the actual temperature command @@ -264,7 +260,7 @@ def printerChamberCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + if not isinstance(offset, (int, float)) or not -50 <= offset <= 50: abort(400, description="offset is invalid") # set the offsets @@ -316,7 +312,7 @@ def printerPrintheadCommand(): for axis in valid_axes: if axis in data: value = data[axis] - if not isinstance(value, (int, long, float)): + if not isinstance(value, (int, float)): abort(400, description="axis value is invalid") validated_values[axis] = value @@ -340,7 +336,7 @@ def printerPrintheadCommand(): elif command == "feedrate": factor = data["factor"] - if not isinstance(factor, (int, long, float)): + if not isinstance(factor, (int, float)): abort(400, description="factor is invalid") try: printer.feed_rate(factor, tags=tags) @@ -470,7 +466,7 @@ def _get_temperature_data(preprocessor): tempHistory = printer.get_temperature_history() limit = 300 - if "limit" in request.values and unicode(request.values["limit"]).isnumeric(): + if "limit" in request.values and str(request.values["limit"]).isnumeric(): limit = int(request.values["limit"]) history = list(tempHistory) diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py index 01c69675c..55644eb45 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,7 +6,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy from flask import abort, jsonify, request, url_for -from past.builtins import basestring from octoprint.access.permissions import Permissions from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError @@ -70,7 +66,7 @@ def printerProfilesAdd(): abort(400, description="profile is missing") base_profile = printerProfileManager.get_default() - if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring): + if "basedOn" in json_data and isinstance(json_data["basedOn"], str): other_profile = printerProfileManager.get(json_data["basedOn"]) if other_profile is not None: base_profile = other_profile diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index a3d5dd7c6..db6c42b21 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -10,7 +7,6 @@ import re from flask import abort, jsonify, request from flask_login import current_user -from past.builtins import basestring import octoprint.plugin import octoprint.util @@ -1025,7 +1021,7 @@ def _saveSettings(data): for name, script in data["scripts"]["gcode"].items(): if name == "snippets": continue - if not isinstance(script, basestring): + if not isinstance(script, str): continue s.saveScript( "gcode", name, script.replace("\r\n", "\n").replace("\r", "\n") diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 11ab033f8..f2dd80b42 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py index 7863a9c01..3f7180fab 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -151,14 +148,14 @@ def executeSystemCommand(source, command): ) ) else: - logger.info("Performing command for {}:{}".format(source, command)) + logger.info(f"Performing command for {source}:{command}") try: if "before" in command_spec and callable(command_spec["before"]): command_spec["before"]() except Exception as e: if not do_ignore: - error = 'Command "before" for {}:{} failed: {}'.format(source, command, e) + error = f'Command "before" for {source}:{command} failed: {e}' logger.warning(error) abort(500, description=error) @@ -201,7 +198,7 @@ def executeSystemCommand(source, command): except Exception as e: if not do_ignore: - error = "Command for {}:{} failed: {}".format(source, command, e) + error = f"Command for {source}:{command} failed: {e}" logger.warning(error) abort(500, error) @@ -328,7 +325,7 @@ def _get_plugin_command_specs(plugin=None): specs[action] = copied except Exception: logging.getLogger(__name__).exception( - "Error while fetching additional actions from plugin {}".format(name), + f"Error while fetching additional actions from plugin {name}", extra={"plugin": name}, ) return specs @@ -352,7 +349,7 @@ def _get_custom_command_specs(): action = spec["action"] if action == "divider": dividers += 1 - action = "divider_{}".format(dividers) + action = f"divider_{dividers}" specs[action] = copied return specs diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 8091b3432..023e76c9c 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -8,6 +5,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import logging import os import threading +from urllib.parse import quote as urlquote from flask import abort, jsonify, request, url_for @@ -24,11 +22,6 @@ from octoprint.server.util.flask import ( ) from octoprint.settings import settings, valid_boolean_trues -try: - from urllib.parse import quote as urlquote -except ImportError: - from urllib import quote as urlquote # noqa: F401 - _DATA_FORMAT_VERSION = "v2" # ~~ timelapse handling @@ -193,9 +186,9 @@ def deleteTimelapse(filename): os.remove(full_path) except Exception as ex: logging.getLogger(__file__).exception( - "Error deleting timelapse file {}".format(full_path) + f"Error deleting timelapse file {full_path}" ) - abort(500, description="Unexpected error: {}".format(ex)) + abort(500, description=f"Unexpected error: {ex}") if ( octoprint.timelapse.valid_timelapse_thumbnail(thumb_path) @@ -208,7 +201,7 @@ def deleteTimelapse(filename): except Exception as ex: # Do not treat this as an error, log and ignore logging.getLogger(__file__).warning( - "Unable to delete thumbnail {} ({})".format(thumb_path, ex) + f"Unable to delete thumbnail {thumb_path} ({ex})" ) return getTimelapseData() diff --git a/src/octoprint/server/api/users.py b/src/octoprint/server/api/users.py index 905468121..056277148 100644 --- a/src/octoprint/server/api/users.py +++ b/src/octoprint/server/api/users.py @@ -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) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py index 5568d36cc..b2134caea 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,7 +6,7 @@ import base64 import logging import sys -PY3 = sys.version_info[0] == 3 +PY3 = sys.version_info[0] == 3 # should now always be true, kept for plugins import flask as _flask import flask_login @@ -19,7 +16,7 @@ import octoprint.timelapse import octoprint.vendor.flask_principal as flask_principal from octoprint.plugin import plugin_manager from octoprint.settings import settings -from octoprint.util import deprecated, to_unicode +from octoprint.util import deprecated, to_str from . import flask, sockjs, tornado, watchdog # noqa: F401 @@ -260,7 +257,7 @@ def get_user_for_authorization_header(header): header = header.replace("Basic ", "", 1) try: - header = to_unicode(base64.b64decode(header)) + header = to_str(base64.b64decode(header)) except TypeError: return None @@ -314,7 +311,7 @@ def get_authorization_header(request): def get_plugin_hash(): from octoprint.plugin import plugin_manager - plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version) + plugin_signature = lambda impl: f"{impl._identifier}:{impl._plugin_version}" template_plugins = list( map( plugin_signature, diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 3a09e34f9..ab656d695 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - from flask import make_response __author__ = "Gina Häußge " @@ -24,7 +21,6 @@ import tornado.web import webassets.updater import webassets.utils from cachelib import BaseCache -from past.builtins import basestring, long from werkzeug.local import LocalProxy from werkzeug.utils import cached_property @@ -38,11 +34,6 @@ from octoprint.util import DefaultOrderedDict, deprecated, yaml 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 @@ -68,11 +59,11 @@ def enable_additional_translations(default_locale="en", additional_folders=None) if not os.path.isdir(dirname): return [] result = [] - for entry in scandir(dirname): + for entry in os.scandir(dirname): locale_dir = os.path.join(entry.path, "LC_MESSAGES") if not os.path.isdir(locale_dir): continue - if any(filter(lambda x: x.name.endswith(".mo"), scandir(locale_dir))): + if any(filter(lambda x: x.name.endswith(".mo"), os.scandir(locale_dir))): result.append(Locale.parse(entry.name)) return result @@ -159,9 +150,7 @@ def enable_additional_translations(default_locale="en", additional_folders=None) ) break else: - logger.debug( - "No translations for locale {} in core folders".format(locale) - ) + logger.debug(f"No translations for locale {locale} in core folders") translations = translations.merge(core_translations) ctx.babel_translations = translations @@ -241,7 +230,7 @@ def fix_flask_jsonify(): # ~~ WSGI environment wrapper for reverse proxying -class ReverseProxiedEnvironment(object): +class ReverseProxiedEnvironment: @staticmethod def to_header_candidates(values): if values is None: @@ -524,7 +513,7 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface): def save_session(self, app, session, response): if flask.g.get("login_via_apikey", False): return - return super(OctoPrintSessionInterface, self).save_session(app, session, response) + return super().save_session(app, session, response) # ~~ jinja environment @@ -580,7 +569,7 @@ def _local_networks(): continue local_networks.add(network) - logger.debug("Added network {} to localNetworks".format(network)) + logger.debug(f"Added network {network} to localNetworks") if network.version == 4: network_v6 = network.ipv6() @@ -629,9 +618,7 @@ def passive_login(): def determine_user(u): if not u.is_anonymous and u.is_active: # known active user - logger.info( - "Passively logging in user {} from {}".format(u.get_id(), remote_address) - ) + logger.info(f"Passively logging in user {u.get_id()} from {remote_address}") elif ( settings().getBoolean(["accessControl", "autologinLocal"]) @@ -910,7 +897,7 @@ def cache_check_status_code(response, valid): return response.status_code not in valid -class PreemptiveCache(object): +class PreemptiveCache: def __init__(self, cachefile): self.cachefile = cachefile self.environment = None @@ -963,9 +950,7 @@ class PreemptiveCache(object): entries = cleanup_function(root, entries) if not entries: del all_data[root] - self._logger.debug( - "Removed root {} from preemptive cache".format(root) - ) + self._logger.debug(f"Removed root {root} from preemptive cache") elif len(entries) < old_count: all_data[root] = entries self._logger.debug( @@ -982,13 +967,13 @@ class PreemptiveCache(object): with self._lock: try: cache_data = yaml.load_from_file(path=self.cachefile) - except IOError as e: + except OSError as e: import errno if e.errno != errno.ENOENT: raise except Exception: - self._logger.exception("Error while reading {}".format(self.cachefile)) + self._logger.exception(f"Error while reading {self.cachefile}") if cache_data is None: cache_data = {} @@ -1011,7 +996,7 @@ class PreemptiveCache(object): with atomic_write(self.cachefile, "wt", max_permissions=0o666) as handle: yaml.save_to_file(data, file=handle, pretty=True) except Exception: - self._logger.exception("Error while writing {}".format(self.cachefile)) + self._logger.exception(f"Error while writing {self.cachefile}") def set_data(self, root, data): with self._lock: @@ -1060,12 +1045,12 @@ class PreemptiveCache(object): to_persist = copy.deepcopy(data) to_persist["_timestamp"] = time.time() to_persist["_count"] = 1 - self._logger.info("Adding entry for {} and {!r}".format(root, to_persist)) + self._logger.info(f"Adding entry for {root} and {to_persist!r}") else: to_persist["_timestamp"] = time.time() to_persist["_count"] = to_persist.get("_count", 0) + 1 self._logger.debug( - "Updating timestamp and counter for {} and {!r}".format(root, data) + f"Updating timestamp and counter for {root} and {data!r}" ) self.set_data(root, [to_persist] + other) @@ -1104,7 +1089,7 @@ def preemptively_cached(cache, data, unless=None): cache.record(data, unless=unless) except Exception: logging.getLogger(__name__).exception( - "Error while recording preemptive cache entry: {!r}".format(data) + f"Error while recording preemptive cache entry: {data!r}" ) return f(*args, **kwargs) @@ -1149,7 +1134,7 @@ def lastmodified(date): if callable(result): result = result(rv) - if not isinstance(result, basestring): + if not isinstance(result, str): from werkzeug.http import http_date result = http_date(result) @@ -1268,7 +1253,7 @@ def with_revalidation_checking( # set last modified header if not already set if lm and response.headers.get("Last-Modified", None) is None: - if not isinstance(lm, basestring): + if not isinstance(lm, str): from werkzeug.http import http_date lm = http_date(lm) @@ -1299,7 +1284,7 @@ def check_lastmodified(lastmodified): from datetime import datetime - if isinstance(lastmodified, (int, long, float)): + if isinstance(lastmodified, (int, float)): # max(86400, lastmodified) is workaround for https://bugs.python.org/issue29097, # present in CPython 3.6.x up to 3.7.1. # diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index 4fb257a73..763824862 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -11,7 +8,6 @@ import threading import time import wrapt -from past.builtins import basestring import octoprint.access.users import octoprint.events @@ -186,9 +182,9 @@ class PrinterStateConnection( def __str__(self): if self._remoteAddress: - return "{!r} connected to {}".format(self, self._remoteAddress) + return f"{self!r} connected to {self._remoteAddress}" else: - return "Unconnected {!r}".format(self) + return f"Unconnected {self!r}" def on_open(self, info): self._pluginManager.register_message_receiver(self.on_plugin_message) @@ -294,7 +290,7 @@ class PrinterStateConnection( self._on_login(user) else: self._logger.warning( - "Unknown user/session combo: {}:{}".format(user_id, user_session) + f"Unknown user/session combo: {user_id}:{user_session}" ) self._on_logout() @@ -333,7 +329,7 @@ class PrinterStateConnection( raise ValueError("value must be a list or boolean") def regex_or_boolean(value): - if isinstance(value, basestring): + if isinstance(value, str): try: return re.compile(value) except Exception: @@ -548,9 +544,7 @@ class PrinterStateConnection( and hasattr(self._user, "session") and user.session == self._user.session ): - self._logger.info( - "User {} logged out, logging out on socket".format(user.get_id()) - ) + self._logger.info(f"User {user.get_id()} logged out, logging out on socket") self._on_logout() if stale: @@ -564,7 +558,7 @@ class PrinterStateConnection( def on_user_removed(self, userid): if self._user.get_id() == userid: - self._logger.info("User {} deleted, logging out on socket".format(userid)) + self._logger.info(f"User {userid} deleted, logging out on socket") self._on_logout() self._sendReauthRequired("removed") @@ -595,7 +589,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user) except Exception: self._logger.exception( - "Error processing register hook handler for plugin {}".format(name), + f"Error processing register hook handler for plugin {name}", extra={"plugin": name}, ) @@ -660,7 +654,7 @@ class PrinterStateConnection( proceed = proceed and hook(self, self._user, type, payload) except Exception: self._logger.exception( - "Error processing emit hook handler from plugin {}".format(name), + f"Error processing emit hook handler from plugin {name}", extra={"plugin": name}, ) @@ -703,7 +697,7 @@ class PrinterStateConnection( except Exception as e: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( - "Could not send message to client {}".format(self._remoteAddress) + f"Could not send message to client {self._remoteAddress}" ) else: self._logger.warning( @@ -726,7 +720,7 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) @@ -759,6 +753,6 @@ class PrinterStateConnection( hook(self, self._user) except Exception: self._logger.exception( - "Error processing authed hook handler for plugin {}".format(name), + f"Error processing authed hook handler for plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 696fef5b9..6d1b75780 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -10,6 +7,7 @@ import mimetypes import os import re import sys +from urllib.parse import urlparse import tornado import tornado.escape @@ -22,17 +20,9 @@ import tornado.iostream import tornado.tcpserver import tornado.util import tornado.web -from past.builtins import basestring, unicode import octoprint.util -try: - from urllib.parse import urlparse # py3 -except ImportError: - from urlparse import urlparse # py2 - -from . import PY3 - def fix_json_encode(): """ @@ -646,23 +636,16 @@ def _extended_header_value(value): if value.lower().startswith("iso-8859-1'") or value.lower().startswith("utf-8'"): # RFC 5987 section 3.2 - try: - from urllib import unquote - except ImportError: - from urllib.parse import unquote + from urllib.parse import unquote + encoding, _, value = value.split("'", 2) - if PY3: - return unquote(value, encoding=encoding) - else: - return unquote(octoprint.util.to_bytes(value, encoding="iso-8859-1")).decode( - encoding - ) + return unquote(value, encoding=encoding) else: # no encoding provided, strip potentially present quotes and call it a day - return octoprint.util.to_unicode(_strip_value_quotes(value), encoding="utf-8") + return octoprint.util.to_str(_strip_value_quotes(value), encoding="utf-8") -class WsgiInputContainer(object): +class WsgiInputContainer: """ A WSGI container for use with Tornado that allows supplying the request body to be used for ``wsgi.input`` in the generated WSGI environment upon call. @@ -774,7 +757,7 @@ class WsgiInputContainer(object): # determine the request_body to supply as wsgi.input if body is not None: - if isinstance(body, (bytes, str, unicode)): + if isinstance(body, (bytes, str)): request_body = io.BytesIO(tornado.escape.utf8(body)) else: request_body = body @@ -1215,7 +1198,7 @@ class LargeResponseHandler( etag = str(self.get_content_version(self.absolute_path)) if not etag.endswith('"'): - etag = '"{}"'.format(etag) + etag = f'"{etag}"' return etag # noinspection PyAttributeOutsideInit @@ -1359,7 +1342,7 @@ class UrlProxyHandler( if not extension: return None - return "{}{}".format(self._basename, extension) + return f"{self._basename}{extension}" class StaticDataHandler( @@ -1402,7 +1385,7 @@ class DeprecatedEndpointHandler(CorsSupportMixin, tornado.web.RequestHandler): def _handle_method(self, *args, **kwargs): to_url = self._url.format(*args) self._logger.info( - "Redirecting deprecated endpoint {} to {}".format(self.request.path, to_url) + f"Redirecting deprecated endpoint {self.request.path} to {to_url}" ) self.redirect(to_url, permanent=True) @@ -1448,7 +1431,7 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): def normalize_files(self, files): result = [] for f in files: - if isinstance(f, basestring): + if isinstance(f, str): result.append({"path": f}) elif isinstance(f, dict) and ("path" in f or "iter" in f or "content" in f): result.append(f) @@ -1460,7 +1443,7 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): if self._as_attachment: self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(self.get_attachment_name()), + f'attachment; filename="{self.get_attachment_name()}"', ) import zipstream @@ -1524,7 +1507,7 @@ class DynamicZipBundleHandler(StaticZipBundleHandler): self._access_validator(self.request) files = list( - map(octoprint.util.to_unicode, self.request.query_arguments.get("files", [])) + map(octoprint.util.to_str, self.request.query_arguments.get("files", [])) ) return self._get_files_zip(files) @@ -1544,7 +1527,7 @@ class DynamicZipBundleHandler(StaticZipBundleHandler): raise tornado.web.HTTPError(400) return self._get_files_zip( - list(map(octoprint.util.to_unicode, data.get("files", []))) + list(map(octoprint.util.to_str, data.get("files", []))) ) def _get_files_zip(self, files): @@ -1610,7 +1593,7 @@ class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler): self.set_header("Content-Type", "application/zip") self.set_header( "Content-Disposition", - 'attachment; filename="{}"'.format(get_systeminfo_bundle_name()), + f'attachment; filename="{get_systeminfo_bundle_name()}"', ) for chunk in z: @@ -1642,7 +1625,7 @@ class GlobalHeaderTransform(tornado.web.OutputTransform): removed_headers = [] return type( - octoprint.util.to_native_str(name), + name, (GlobalHeaderTransform,), { "HEADERS": headers, diff --git a/src/octoprint/server/util/watchdog.py b/src/octoprint/server/util/watchdog.py index 4f024405c..aa36d8fe6 100644 --- a/src/octoprint/server/util/watchdog.py +++ b/src/octoprint/server/util/watchdog.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -18,37 +15,6 @@ import octoprint.filemanager.util import octoprint.util -def fix_scandir(): - try: - from os import scandir - - # nothing to fix, natively available, return - return - - except ImportError: - # not natively available, use backport - import watchdog.utils.dirsnapshot - from scandir import scandir - - OriginalDirectorySnapshot = watchdog.utils.dirsnapshot.DirectorySnapshot - - class FixedDirectorySnapshot(OriginalDirectorySnapshot): - def __init__(self, listdir=scandir, *args, **kwargs): - OriginalDirectorySnapshot.__init__(self, listdir=listdir, *args, **kwargs) - - watchdog.utils.dirsnapshot.DirectorySnapshot = FixedDirectorySnapshot - - import watchdog.observers.polling - - OriginalPollingEmitter = watchdog.observers.polling.PollingEmitter - - class FixedPollingEmitter(OriginalPollingEmitter): - def __init__(self, listdir=scandir, *args, **kwargs): - OriginalPollingEmitter.__init__(self, listdir=listdir, *args, **kwargs) - - watchdog.observers.polling.PollingEmitter = FixedPollingEmitter - - class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): """ @@ -71,14 +37,9 @@ 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 - def _recursive_scandir(path): """Recursively yield DirEntry objects for given directory.""" - for entry in scandir(path): + for entry in os.scandir(path): if entry.is_dir(follow_symlinks=False): for entry in _recursive_scandir(entry.path): yield entry @@ -95,7 +56,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): if not self._valid_path(path): continue - self._logger.info("Found {}, trying to add it".format(path)) + self._logger.info(f"Found {path}, trying to add it") self._upload(path) self._logger.info("... initial scan done.") @@ -185,7 +146,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): # file is still there - that should only happen if something went wrong, so mark it as failed # noinspection PyBroadException try: - shutil.move(path, "{}.failed".format(path)) + shutil.move(path, f"{path}.failed") except Exception: # something went really wrong here.... but we can't do anything about it, so just log it self._logger.exception( @@ -228,7 +189,7 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler): last_size = new_size time.sleep(interval) - self._logger.debug("File at {} is stable, moving it".format(path)) + self._logger.debug(f"File at {path} is stable, moving it") self._upload(path) def _valid_path(self, path): diff --git a/src/octoprint/server/util/webassets.py b/src/octoprint/server/util/webassets.py index 2c44b1ea7..a9e99f314 100644 --- a/src/octoprint/server/util/webassets.py +++ b/src/octoprint/server/util/webassets.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -9,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 @@ -57,7 +50,7 @@ class UrlRewriter(PatternRewriter): ) self.output_url = self.ctx.resolver.resolve_output_to_url(self.ctx, output) - return super(UrlRewriter, self).input(_in, out, **kw) + return super().input(_in, out, **kw) def replace_url(self, url): return replace_url(self.source_url, self.output_url, url) diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 56b5ce61a..4220d19c7 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 base64 import datetime -import io import logging import os import re @@ -24,7 +20,6 @@ from flask import ( send_from_directory, url_for, ) -from past.builtins import basestring import octoprint.plugin from octoprint.access.permissions import OctoPrintPermission, Permissions @@ -45,7 +40,7 @@ from octoprint.server import ( # noqa: F401 ) from octoprint.server.util import has_permissions, require_login_with from octoprint.settings import settings -from octoprint.util import sv, to_bytes, to_unicode +from octoprint.util import sv, to_bytes, to_str from octoprint.util.version import get_python_version_string from . import util @@ -108,7 +103,7 @@ def _preemptive_data( d.update(data) except Exception: _logger.exception( - "Error collecting data for preemptive cache from plugin {}".format(key) + f"Error collecting data for preemptive cache from plugin {key}" ) # add additional request data if we have any @@ -133,7 +128,7 @@ def _cache_key(ui, url=None, locale=None, additional_key_data=None): if locale is None: locale = g.locale.language if g.locale else "en" - k = "ui:{}:{}:{}".format(ui, url, locale) + k = f"ui:{ui}:{url}:{locale}" if callable(additional_key_data): try: ak = additional_key_data() @@ -164,7 +159,7 @@ def _add_additional_assets(hook): result += assets except Exception: _logger.exception( - "Error fetching theming CSS to include from plugin {}".format(name), + f"Error fetching theming CSS to include from plugin {name}", extra={"plugin": name}, ) return result @@ -282,7 +277,7 @@ def in_cache(): break except Exception: _logger.exception( - "Error while calling plugin {}, skipping it".format(plugin._identifier), + f"Error while calling plugin {plugin._identifier}, skipping it", extra={"plugin": plugin._identifier}, ) else: @@ -306,9 +301,7 @@ def in_cache(): ) return response elif util.flask.is_in_cache(key): - _logger.info( - "Found path {} in cache (key: {}), signaling as cached".format(path, key) - ) + _logger.info(f"Found path {path} in cache (key: {key}), signaling as cached") return response elif util.flask.is_cache_bypassed(key): _logger.info( @@ -318,9 +311,7 @@ def in_cache(): ) return response else: - _logger.debug( - "Path {} not yet cached (key: {}), signaling as missing".format(path, key) - ) + _logger.debug(f"Path {path} not yet cached (key: {key}), signaling as missing") return abort(404) @@ -384,9 +375,7 @@ def index(): wizard_active(_templates.get(locale)), ] + sorted( [ - "{}:{}".format( - to_unicode(k, errors="replace"), to_unicode(v, errors="replace") - ) + "{}:{}".format(to_str(k, errors="replace"), to_str(v, errors="replace")) for k, v in _plugin_vars.items() ] ) @@ -488,7 +477,7 @@ def index(): ) ) - if lastmodified and not isinstance(lastmodified, basestring): + if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) @@ -630,7 +619,7 @@ def index(): if forced_view: # we have view forced by the preemptive cache - _logger.debug("Forcing rendering of view {}".format(forced_view)) + _logger.debug(f"Forcing rendering of view {forced_view}") if forced_view != "_default": plugin = pluginManager.get_plugin_info(forced_view, require_enabled=True) if plugin is not None and isinstance( @@ -717,7 +706,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): permissions = [permission.as_dict() for permission in Permissions.all()] filetypes = list(sorted(full_extension_tree().keys())) - extensions = list(map(lambda ext: ".{}".format(ext), get_all_extensions())) + extensions = list(map(lambda ext: f".{ext}", get_all_extensions())) # ~~ prepare full set of template vars for rendering @@ -803,13 +792,13 @@ def fetch_template_data(refresh=False): # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 - return "0:{}".format(to_unicode(d[0])) + return "0:{}".format(to_str(d[0])) elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones - return "1:{}".format(to_unicode(d[0])) + return "1:{}".format(to_str(d[0])) else: # Finally everything else - return "2:{}".format(to_unicode(d[0])) + return "2:{}".format(to_str(d[0])) template_sorting = { "navbar": {"add": "prepend", "key": None}, @@ -1589,7 +1578,7 @@ def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None): files = _get_all_translationfiles(locale, domain) if lastmodified is None: lastmodified = _compute_date(files) - if lastmodified and not isinstance(lastmodified, basestring): + if lastmodified and not isinstance(lastmodified, str): from werkzeug.http import http_date lastmodified = http_date(lastmodified) @@ -1706,7 +1695,7 @@ def _get_translations(locale, domain): def messages_from_po(path, locale, domain): messages = {} - with io.open(path, mode="rt", encoding="utf-8") as f: + with open(path, mode="rt", encoding="utf-8") as f: catalog = read_po(f, locale=locale, domain=domain) for message in catalog: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 34122cd65..29213ab01 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ This module represents OctoPrint's settings management. Within this module the default settings for the core application are defined and the instance of the :class:`Settings` is held, which offers getter and setter @@ -16,39 +15,23 @@ of various types and the configuration file itself. :members: :undoc-members: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __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 fnmatch -import io import logging import os import re import sys import time +from collections import ChainMap +from collections.abc import KeysView # noinspection PyCompatibilitys -from past.builtins import basestring from yaml import YAMLError -try: - from collections import ChainMap -except ImportError: - from chainmap import ChainMap - -try: - from collections.abc import KeysView -except ImportError: - from collections import KeysView - -try: - from os import scandir -except ImportError: - from scandir import scandir - from octoprint.util import ( CaseInsensitiveSet, atomic_write, @@ -642,7 +625,7 @@ class HierarchicalChainMap(ChainMap): return cls._hierarchy_for_key(key, node) -class Settings(object): +class Settings: """ The :class:`Settings` class allows managing all of OctoPrint's settings. It takes care of initializing the settings directory, loading the configuration from ``config.yaml``, persisting changes to disk etc and provides access @@ -827,7 +810,7 @@ class Settings(object): lambda x: key + "/" + x, self._get_templates(scripts[key]) ) ) - elif isinstance(scripts[key], basestring): + elif isinstance(scripts[key], str): templates.append(key) return templates @@ -1024,7 +1007,7 @@ class Settings(object): def load(self, migrate=False): 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: + with open(self._configfile, encoding="utf-8", errors="replace") as f: try: self._config = yaml.load_from_file(file=f) self._mtime = self.last_modified @@ -1064,17 +1047,15 @@ class Settings(object): try: overlay_config = self.load_overlay(path, migrate=migrate) self.add_overlay(overlay_config) - self._logger.info("Added config overlay from {}".format(path)) + self._logger.info(f"Added config overlay from {path}") except Exception: - self._logger.exception( - "Could not add config overlay from {}".format(path) - ) + self._logger.exception(f"Could not add config overlay from {path}") if os.path.isfile(overlay): process(overlay) elif os.path.isdir(overlay): - for entry in scandir(overlay): + for entry in os.scandir(overlay): name = entry.name path = entry.path @@ -1093,7 +1074,7 @@ class Settings(object): self._logger.exception("Error loading overlay from callable") return - if isinstance(overlay, basestring): + if isinstance(overlay, str): if os.path.exists(overlay) and os.path.isfile(overlay): config = yaml.load_from_file(path=overlay) elif isinstance(overlay, dict): @@ -1105,7 +1086,7 @@ class Settings(object): if not isinstance(config, dict): raise ValueError( - "Configuration data must be a dict but is a {}".format(config.__class__) + f"Configuration data must be a dict but is a {config.__class__}" ) if migrate: @@ -1888,7 +1869,7 @@ class Settings(object): return value if isinstance(value, (int, float)): return value != 0 - if isinstance(value, basestring): + if isinstance(value, str): return value.lower() in valid_boolean_trues return value is not None @@ -2021,7 +2002,7 @@ class Settings(object): preprocessors=None, error_on_path=False, *args, - **kwargs + **kwargs, ): if not path: if error_on_path: @@ -2139,7 +2120,7 @@ class Settings(object): def setBoolean(self, path, value, **kwargs): if value is None or isinstance(value, bool): self.set(path, value, **kwargs) - elif isinstance(value, basestring) and value.lower() in valid_boolean_trues: + elif isinstance(value, str) and value.lower() in valid_boolean_trues: self.set(path, True, **kwargs) else: self.set(path, False, **kwargs) @@ -2214,15 +2195,15 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab 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(f"Folder at {folder} appears to be a broken symlink") elif create: # non existing, but we are allowed to create it try: os.makedirs(folder) except Exception: - logger.exception("Could not create {}".format(folder)) - raise IOError( + logger.exception(f"Could not create {folder}") + raise OSError( "Folder for type {} at {} does not exist and creation failed".format( type, folder ) @@ -2230,11 +2211,11 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab else: # not extisting, not allowed to create it - raise IOError("No such folder: {}".format(folder)) + raise OSError(f"No such folder: {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(f"Expected a folder at {folder} but found a file instead") elif check_writable: # make sure we can also write into the folder @@ -2242,16 +2223,16 @@ def _validate_folder(folder, create=True, check_writable=True, deep_check_writab 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 # to determine whether things are *actually* writable testfile = os.path.join(folder, ".testballoon.txt") try: - with io.open(testfile, "wt", encoding="utf-8") as f: + with open(testfile, "wt", encoding="utf-8") as f: f.write("test") os.remove(testfile) except Exception: - logger.exception("Could not write test file to {}".format(testfile)) - raise IOError(error) + logger.exception(f"Could not write test file to {testfile}") + raise OSError(error) diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py index 377369f87..a005ff8fb 100644 --- a/src/octoprint/slicing/__init__.py +++ b/src/octoprint/slicing/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ In this module the slicing support of OctoPrint is encapsulated. @@ -11,7 +10,6 @@ In this module the slicing support of OctoPrint is encapsulated. .. autoclass:: SlicingManager :members: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -37,7 +35,7 @@ from .exceptions import ( ) -class SlicingProfile(object): +class SlicingProfile: """ A wrapper for slicing profiles, both meta data and actual profile data. @@ -61,7 +59,7 @@ class SlicingProfile(object): self.default = default -class TemporaryProfile(object): +class TemporaryProfile: """ A wrapper for a temporary slicing profile to be used for a slicing job, based on a :class:`SlicingProfile` with optional ``overrides`` applied through the supplied ``save_profile`` method. @@ -109,7 +107,7 @@ class TemporaryProfile(object): pass -class SlicingManager(object): +class SlicingManager: """ The :class:`SlicingManager` is responsible for managing available slicers and slicing profiles. @@ -426,7 +424,7 @@ class SlicingManager(object): 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 @@ -534,7 +532,7 @@ class SlicingManager(object): 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 @@ -726,11 +724,9 @@ class SlicingManager(object): name = self._sanitize(name) - path = os.path.join( - self.get_slicer_profile_path(slicer), "{name}.profile".format(name=name) - ) + path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile") 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() ) @@ -784,7 +780,7 @@ class SlicingManager(object): 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 diff --git a/src/octoprint/slicing/exceptions.py b/src/octoprint/slicing/exceptions.py index 07faf215a..0036890bb 100644 --- a/src/octoprint/slicing/exceptions.py +++ b/src/octoprint/slicing/exceptions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ Slicing related exceptions. @@ -25,7 +24,6 @@ Slicing related exceptions. :show-inheritance: """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -69,7 +67,7 @@ class SlicerNotConfigured(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "Slicer not configured: {slicer}".format(slicer=slicer) + self.message = f"Slicer not configured: {slicer}" class UnknownSlicer(SlicerException): @@ -79,7 +77,7 @@ class UnknownSlicer(SlicerException): def __init__(self, slicer, *args, **kwargs): SlicerException.__init__(self, slicer, *args, **kwargs) - self.message = "No such slicer: {slicer}".format(slicer=slicer) + self.message = f"No such slicer: {slicer}" class ProfileException(Exception): diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 526645385..c9bb3f3e7 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -18,7 +18,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { self._lastProcessingTimesSize = 20; self._safeModePopup = undefined; - self._python2Popup = undefined; self.increaseThrottle = function () { self.setThrottle(self._throttleFactor + 1); @@ -234,22 +233,6 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { }); } - // process python version - if (self._python2Popup) self._python2Popup.remove(); - if (PYTHON_VERSION && PYTHON_VERSION.startsWith("2.")) { - self._python2Popup = new PNotify({ - title: gettext("You are still running Python 2"), - text: _.sprintf( - gettext( - "

Python 2 is end-of-life as of January 1st 2020. While OctoPrint currently still supports running under Python 2, a future version will remove support and require Python 3. You should upgrade as soon as possible!

Please refer to the FAQ for recommended update workflows:

" - ) + - "

How to migrate to Python 3

", - {reason: _.escape(reason)} - ), - hide: false - }); - } - // if the offline overlay is still showing, now's a good time to // hide it, plus reload the camera feed if it's currently displayed if ($("#offline_overlay").is(":visible")) { diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py index 908b5c3a7..3dc782b52 100644 --- a/src/octoprint/timelapse.py +++ b/src/octoprint/timelapse.py @@ -1,27 +1,19 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" +import collections import datetime import fnmatch -import io +import glob 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 @@ -31,15 +23,9 @@ from octoprint.events import Events, eventManager from octoprint.plugin import plugin_manager from octoprint.settings import settings from octoprint.util import get_fully_qualified_classname as fqcn -from octoprint.util import monotonic_time, sv +from octoprint.util import sv from octoprint.util.commandline import CommandlineCaller -try: - from os import scandir -except ImportError: - from scandir import scandir - - # currently configured timelapse current = None @@ -123,7 +109,7 @@ def _extract_prefix(filename): """ >>> _extract_prefix("some_long_filename_without_hyphen.jpg") >>> _extract_prefix("-first_char_is_hyphen.jpg") - >>> _extract_prefix("some_long_filename_with-stuff.jpg") # doctest: +ALLOW_UNICODE + >>> _extract_prefix("some_long_filename_with-stuff.jpg") 'some_long_filename_with' """ pos = filename.rfind("-") @@ -145,7 +131,7 @@ def last_modified_unrendered(): def get_finished_timelapses(): files = [] basedir = settings().getBaseFolder("timelapse", check_writable=False) - for entry in scandir(basedir): + for entry in os.scandir(basedir): if util.is_hidden_path(entry.path) or not valid_timelapse(entry.path): continue @@ -181,7 +167,7 @@ def get_unrendered_timelapses(): lambda: {"count": 0, "size": None, "bytes": 0, "date": None, "timestamp": None} ) - for entry in scandir(basedir): + for entry in os.scandir(basedir): if not fnmatch.fnmatch(entry.name, "*.jpg"): continue @@ -229,18 +215,18 @@ def get_unrendered_timelapses(): def delete_unrendered_timelapse(name): global _cleanup_lock - pattern = "{}*.jpg".format(util.glob_escape(name)) + pattern = "{}*.jpg".format(glob.escape(name)) basedir = settings().getBaseFolder("timelapse_tmp") with _cleanup_lock: - for entry in scandir(basedir): + for entry in os.scandir(basedir): try: if fnmatch.fnmatch(entry.name, pattern): os.remove(entry.path) except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) @@ -279,7 +265,7 @@ def delete_old_unrendered_timelapses(): prefixes_to_clean = [] with _cleanup_lock: - for entry in scandir(basedir): + for entry in os.scandir(basedir): try: prefix = _extract_prefix(entry.name) if prefix is None: @@ -298,14 +284,12 @@ def delete_old_unrendered_timelapses(): except Exception: if logging.getLogger(__name__).isEnabledFor(logging.DEBUG): logging.getLogger(__name__).exception( - "Error while processing file {} during cleanup".format(entry.name) + f"Error while processing file {entry.name} during cleanup" ) for prefix in prefixes_to_clean: delete_unrendered_timelapse(prefix) - logging.getLogger(__name__).info( - "Deleted old unrendered timelapse {}".format(prefix) - ) + logging.getLogger(__name__).info(f"Deleted old unrendered timelapse {prefix}") def _create_render_start_handler(name, gcode=None): @@ -495,7 +479,7 @@ def configure_timelapse(config=None, persist=False): settings().save() -class Timelapse(object): +class Timelapse: QUEUE_ENTRY_TYPE_CAPTURE = "capture" QUEUE_ENTRY_TYPE_CALLBACK = "callback" @@ -721,7 +705,7 @@ class Timelapse(object): ) self._image_number += 1 - self._logger.debug("Capturing image to {}".format(filename)) + self._logger.debug(f"Capturing image to {filename}") entry = { "type": self.__class__.QUEUE_ENTRY_TYPE_CAPTURE, "filename": filename, @@ -767,9 +751,7 @@ class Timelapse(object): eventManager().fire(Events.CAPTURE_START, {"file": filename}) try: - self._logger.debug( - "Going to capture {} from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Going to capture {filename} from {self._snapshot_url}") r = requests.get( self._snapshot_url, stream=True, @@ -778,18 +760,16 @@ class Timelapse(object): ) r.raise_for_status() - with io.open(filename, "wb") as f: + with open(filename, "wb") as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() - self._logger.debug( - "Image {} captured from {}".format(filename, self._snapshot_url) - ) + self._logger.debug(f"Image {filename} captured from {self._snapshot_url}") except Exception as e: self._logger.exception( - "Could not capture image {} from {}".format(filename, self._snapshot_url) + f"Could not capture image {filename} from {self._snapshot_url}" ) self._capture_errors += 1 err = e @@ -888,7 +868,7 @@ class ZTimelapse(Timelapse): return # check if last picture has been less than min_delay ago, if so don't take a picture (anti vase mode...) - now = monotonic_time() + now = time.monotonic() if ( self._min_delay and self._last_snapshot @@ -950,7 +930,7 @@ class TimedTimelapse(Timelapse): self._timer = None -class TimelapseRenderJob(object): +class TimelapseRenderJob: render_job_lock = threading.RLock() @@ -1033,7 +1013,7 @@ class TimelapseRenderJob(object): postfix=self._postfix if self._postfix is not None else "", extension=extension, ) - temporary = os.path.join(self._output_dir, ".{}".format(output_name)) + temporary = os.path.join(self._output_dir, f".{output_name}") output = os.path.join(self._output_dir, output_name) for i in range(4): @@ -1075,7 +1055,7 @@ class TimelapseRenderJob(object): rotate=rotate, watermark=watermark, ) - self._logger.debug("Executing command: {}".format(command_str)) + self._logger.debug(f"Executing command: {command_str}") with self.render_job_lock: try: @@ -1120,7 +1100,7 @@ class TimelapseRenderJob(object): os.remove(temporary) except Exception: self._logger.warning( - "Could not delete temporary timelapse {}".format(temporary) + f"Could not delete temporary timelapse {temporary}" ) self._notify_callback("always", output) @@ -1247,7 +1227,7 @@ class TimelapseRenderJob(object): else "", } - logger.debug("Rendering movie to {}".format(output)) + logger.debug(f"Rendering movie to {output}") return commandline.format(**placeholders) @classmethod @@ -1271,7 +1251,7 @@ class TimelapseRenderJob(object): ### See unit tests in test/timelapse/test_timelapse_renderjob.py # apply pixel format - filters = ["format={}".format(pixfmt)] + filters = [f"format={pixfmt}"] # flip video if configured if hflip: @@ -1303,7 +1283,7 @@ class TimelapseRenderJob(object): def _notify_callback(self, callback, *args, **kwargs): """Notifies registered callbacks of type `callback`.""" - name = "_on_{}".format(callback) + name = f"_on_{callback}" method = getattr(self, name, None) if method is not None and callable(method): method(*args, **kwargs) diff --git a/src/octoprint/users.py b/src/octoprint/users.py index 3022a2562..6f07b90a4 100644 --- a/src/octoprint/users.py +++ b/src/octoprint/users.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Marc Hannappel " __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" diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 37e2f88cc..14fbae76f 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- """ This module bundles commonly used utility methods or helper classes that are used in multiple places within OctoPrint's source code. """ -from __future__ import absolute_import, division, print_function, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -13,10 +11,11 @@ import codecs import collections import contextlib import copy -import io import json import logging import os +import pickle +import queue import re import shutil import sys @@ -26,31 +25,14 @@ import time import traceback import warnings import zlib +from collections.abc import Iterable, MutableMapping, Set from functools import wraps +from glob import escape as glob_escape # noqa: F401 +from time import monotonic as monotonic_time # noqa: F401 from typing import Union -try: - from collections.abc import Iterable, MutableMapping, Set -except ImportError: - # Python 2.7 - from collections import Iterable, MutableMapping, Set - -import past.builtins from frozendict import frozendict -try: - import queue -except ImportError: - import Queue as queue - -try: - import cPickle as pickle # Python 2 has pickle and cPickle, we want cPickle -except ImportError: - import pickle # Python 3 - -# noinspection PyCompatibility -from past.builtins import basestring, unicode - from octoprint import UMASK from octoprint.util.connectivity import ConnectivityChecker # noqa: F401 from octoprint.util.files import ( # noqa: F401 @@ -67,46 +49,48 @@ from octoprint.util.net import ( # noqa: F401 logger = logging.getLogger(__name__) -def to_bytes(s_or_u, encoding="utf-8", errors="strict"): - # type: (Union[unicode, bytes], str, str) -> bytes +def to_bytes( + s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict" +) -> bytes: """ Make sure ``s_or_u`` is a byte string. Arguments: - s_or_u (string or unicode): The value to convert - encoding (string): encoding to use if necessary, see :meth:`python:str.encode` - errors (string): error handling to use if necessary, see :meth:`python:str.encode` + s_or_u (str or bytes): The value to convert + encoding (str): encoding to use if necessary, see :meth:`python:str.encode` + errors (str): error handling to use if necessary, see :meth:`python:str.encode` Returns: bytes: converted bytes. """ if s_or_u is None: return s_or_u - if not isinstance(s_or_u, basestring): + if not isinstance(s_or_u, (str, bytes)): s_or_u = str(s_or_u) - if isinstance(s_or_u, unicode): + if isinstance(s_or_u, str): return s_or_u.encode(encoding, errors=errors) else: return s_or_u -def to_unicode(s_or_u, encoding="utf-8", errors="strict"): - # type: (Union[unicode, bytes], str, str) -> unicode +def to_str( + s_or_u: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict" +) -> str: """ - Make sure ``s_or_u`` is a unicode string. + Make sure ``s_or_u`` is a str. Arguments: - s_or_u (string or unicode): The value to convert - encoding (string): encoding to use if necessary, see :meth:`python:bytes.decode` - errors (string): error handling to use if necessary, see :meth:`python:bytes.decode` + s_or_u (str or bytes): The value to convert + encoding (str): encoding to use if necessary, see :meth:`python:bytes.decode` + errors (str): error handling to use if necessary, see :meth:`python:bytes.decode` Returns: - string: converted string. + str: converted string. """ if s_or_u is None: return s_or_u - if not isinstance(s_or_u, basestring): + if not isinstance(s_or_u, (str, bytes)): s_or_u = str(s_or_u) if isinstance(s_or_u, bytes): @@ -115,16 +99,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_unicode = to_str # left for backwards compatibility +to_native_str = to_str # left for backwards compatibility def sortable_value(value, default_value=""): @@ -138,21 +114,21 @@ sv = sortable_value def pp(value): """ - >>> pp(dict()) # doctest: +ALLOW_UNICODE + >>> pp(dict()) 'dict()' - >>> pp(dict(a=1, b=2, c=3)) # doctest: +ALLOW_UNICODE + >>> pp(dict(a=1, b=2, c=3)) 'dict(a=1, b=2, c=3)' - >>> pp(set()) # doctest: +ALLOW_UNICODE + >>> pp(set()) 'set()' - >>> pp({"a", "b"}) # doctest: +ALLOW_UNICODE + >>> pp({"a", "b"}) "{'a', 'b'}" - >>> pp(["a", "b", "d", "c"]) # doctest: +ALLOW_UNICODE + >>> pp(["a", "b", "d", "c"]) "['a', 'b', 'd', 'c']" - >>> pp(("a", "b", "d", "c")) # doctest: +ALLOW_UNICODE + >>> pp(("a", "b", "d", "c")) "('a', 'b', 'd', 'c')" - >>> pp("foo") # doctest: +ALLOW_UNICODE + >>> pp("foo") "'foo'" - >>> pp([dict(a=1, b=2), {"a", "c", "b"}, (1, 2), None, 1, True, "foo"]) # doctest: +ALLOW_UNICODE + >>> pp([dict(a=1, b=2), {"a", "c", "b"}, (1, 2), None, 1, True, "foo"]) "[dict(a=1, b=2), {'a', 'b', 'c'}, (1, 2), None, 1, True, 'foo']" """ @@ -344,13 +320,6 @@ Returns: """ -to_str = deprecated( - "to_str has been renamed to to_bytes", - includedoc="to_str has been renamed to to_bytes", - since="1.3.11", -)(to_bytes) - - def get_formatted_size(num): """ Formats the given byte count as a human readable rounded size expressed in the most pressing unit among B(ytes), @@ -367,7 +336,7 @@ def get_formatted_size(num): for x in ["B", "KB", "MB", "GB"]: if num < 1024: - return "{:3.1f}{}".format(num, x) + return f"{num:3.1f}{x}" num /= 1024 return "{:3.1f}{}".format(num, "TB") @@ -489,13 +458,13 @@ def get_exception_string(fmt="{type}: '{message}' @ {file}:{function}:{line}"): def sanitize_ascii(line): - if not isinstance(line, basestring): + if not isinstance(line, str): raise ValueError( - "Expected either str or unicode but got {} instead".format( + "Expected str but got {} instead".format( line.__class__.__name__ if line is not None else None ) ) - return to_unicode(line, encoding="ascii", errors="replace").rstrip() + return to_str(line, encoding="ascii", errors="replace").rstrip() def filter_non_ascii(line): @@ -510,7 +479,7 @@ def filter_non_ascii(line): """ try: - to_bytes(to_unicode(line, encoding="ascii"), encoding="ascii") + to_bytes(to_str(line, encoding="ascii"), encoding="ascii") return False except ValueError: return True @@ -518,7 +487,7 @@ def filter_non_ascii(line): def filter_non_utf8(line): try: - to_bytes(to_unicode(line, encoding="utf-8"), encoding="utf-8") + to_bytes(to_str(line, encoding="utf-8"), encoding="utf-8") return False except ValueError: return True @@ -857,8 +826,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): @@ -949,7 +917,7 @@ class DefaultOrderedDict(collections.OrderedDict): ) -class Object(object): +class Object: pass @@ -962,8 +930,8 @@ def guess_mime_type(data): def parse_mime_type(mime): import cgi - if not mime or not isinstance(mime, basestring): - raise ValueError("mime must be a non empty str or unicode") + if not mime or not isinstance(mime, str): + raise ValueError("mime must be a non empty str") mime, params = cgi.parse_header(mime) @@ -1013,17 +981,18 @@ def atomic_write( # Ensure we create the file in the target dir so our move is atomic. See #3719 dir = os.path.dirname(filename) + kwargs = { + "mode": mode, + "prefix": prefix, + "suffix": suffix, + "dir": dir, + "delete": False, + } + if "b" not in mode: + kwargs["encoding"] = encoding - # NamedTemporaryFile doesn't yet have an encoding parameter in py2, so we go the long way - fd, path = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) + fd = tempfile.NamedTemporaryFile(**kwargs) try: - os.close(fd) - - if "b" in mode: - fd = io.open(path, mode=mode) - else: - fd = io.open(path, mode=mode, encoding=encoding) - try: yield fd finally: @@ -1031,8 +1000,7 @@ def atomic_write( os.chmod(fd.name, permissions) shutil.move(fd.name, filename) finally: - # just in case something went wrong and the temporary file is still there, nuke it now - silent_remove(path) + silent_remove(fd.name) @contextlib.contextmanager @@ -1063,32 +1031,7 @@ def temppath(prefix=None, suffix=""): os.remove(temp.name) -if hasattr(tempfile, "TemporaryDirectory"): - # Python 3 - TemporaryDirectory = tempfile.TemporaryDirectory -else: - # Python 2 - class TemporaryDirectory(object): - def __init__(self, suffix="", prefix="tmp", dir=None): - self._path = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) - - @property - def name(self): - return self._path - - def cleanup(self): - try: - os.remove(self._path) - except Exception as exc: - logging.getLogger(__name__).warning( - "Could not delete temporary directory {}: {}".format(self.name, exc) - ) - - def __enter__(self): - return self.name - - def __exit__(self): - self.cleanup() +TemporaryDirectory = tempfile.TemporaryDirectory @deprecated("Please use io.open with '-sig' encoding instead", since="1.8.0") @@ -1109,13 +1052,13 @@ def bom_aware_open(filename, encoding="ascii", mode="r", **kwargs): # these encodings might have a BOM, so let's see if there is one bom = getattr(codecs, potential_bom_attribute) - with io.open(filename, mode="rb") as f: + with open(filename, mode="rb") as f: header = f.read(4) if header.startswith(bom): encoding += "-sig" - return io.open(filename, encoding=encoding, mode=mode, **kwargs) + return open(filename, encoding=encoding, mode=mode, **kwargs) BOMS = { @@ -1138,7 +1081,7 @@ def get_bom(filename, encoding): Returns: (bytes) the BOM or None if there is no BOM. """ - with io.open(filename, mode="rb") as f: + with open(filename, mode="rb") as f: header = f.read(4) for enc, bom in BOMS.items(): @@ -1152,7 +1095,7 @@ def is_hidden_path(path): # we define a None path as not hidden here return False - path = to_unicode(path) + path = to_str(path) filename = os.path.basename(path) if filename.startswith("."): @@ -1175,42 +1118,6 @@ 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 - - def thaw_frozendict(obj): if not isinstance(obj, (dict, frozendict)): raise ValueError("obj must be a dict or frozendict instance") @@ -1234,16 +1141,9 @@ def utmify(link, source=None, medium=None, name=None, term=None, content=None): if source is None: return link + import urllib.parse as urlparse from collections import OrderedDict - - try: - from urllib import urlencode - - import urlparse - except ImportError: - # python 3 - import urllib.parse as urlparse - from urllib.parse import urlencode + from urllib.parse import urlencode # inspired by https://stackoverflow.com/a/2506477 parts = list(urlparse.urlparse(link)) @@ -1501,7 +1401,7 @@ class ResettableTimer(threading.Thread): self.on_reset() -class CountedEvent(object): +class CountedEvent: def __init__(self, value=0, minimum=0, maximum=None, **kwargs): self._counter = 0 self._min = minimum @@ -1576,7 +1476,7 @@ class CountedEvent(object): self._event.set() -class InvariantContainer(object): +class InvariantContainer: def __init__(self, initial_data=None, guarantee_invariant=None): from threading import RLock @@ -1663,7 +1563,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1684,7 +1584,7 @@ class TypedQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -1706,12 +1606,10 @@ class CaseInsensitiveSet(Set): """ def __init__(self, *args): - self.data = { - x.lower() if isinstance(x, past.builtins.basestring) else x for x in args - } + self.data = {x.lower() if isinstance(x, str) else x for x in args} def __contains__(self, item): - if isinstance(item, past.builtins.basestring): + if isinstance(item, str): return item.lower() in self.data else: return item in self.data @@ -1743,7 +1641,7 @@ def fqfn(f): f.__self__.__class__.__module__, f.__self__.__class__.__name__, f.__name__ ) else: - return "{}.{}".format(f.__module__, f.__name__) + return f"{f.__module__}.{f.__name__}" def time_this( @@ -1824,7 +1722,7 @@ def serialize(filename, data, encoding="utf-8", compressed=True): if compressed: serialized = zlib.compress(serialized) - with io.open(filename, "wb") as f: + with open(filename, "wb") as f: f.write(serialized) @@ -1842,7 +1740,7 @@ def deserialize(filename, encoding="utf-8"): Returns: The deserialized data structure """ - with io.open(filename, "rb") as f: + with open(filename, "rb") as f: serialized = f.read() try: diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index 9a1d8807e..4a893cbc1 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge based on work by David Braam" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge & others - Released under terms of the AGPLv3 License" @@ -14,28 +11,16 @@ import contextlib import copy import fnmatch import glob -import io +import logging 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: - from scandir import scandir - -import logging from collections import deque import serial import wrapt -from past.builtins import basestring import octoprint.plugin from octoprint.events import Events, eventManager @@ -54,9 +39,8 @@ from octoprint.util import ( filter_non_utf8, get_bom, get_exception_string, - monotonic_time, sanitize_ascii, - to_unicode, + to_str, ) from octoprint.util.platform import get_os, set_close_exec @@ -177,9 +161,7 @@ Groups will be as follows: * ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions """ -regex_e_positions = re.compile( - r"E(?P\d+):\s*(?P{float})".format(float=regex_float_pattern) -) +regex_e_positions = re.compile(fr"E(?P\d+):\s*(?P{regex_float_pattern})") """Regex for matching multiple E coordinates in a position report. Groups will be as follows: @@ -214,7 +196,7 @@ def serialList(): else: candidates = [] - with scandir("/dev") as it: + with os.scandir("/dev") as it: for entry in it: if regex_serial_devices.match(entry.name): candidates.append(entry.path) @@ -266,7 +248,7 @@ def baudrateList(candidates=None): candidates.insert(0, int(additional)) except Exception: _logger.warning( - "{} is not a valid additional baudrate, ignoring it".format(additional) + f"{additional} is not a valid additional baudrate, ignoring it" ) # blacklisted baudrates @@ -313,7 +295,7 @@ gcodeToEvent = { } -class PositionRecord(object): +class PositionRecord: _standard_attrs = {"x", "y", "z", "e", "f", "t"} @classmethod @@ -349,7 +331,7 @@ class PositionRecord(object): return {attr: getattr(self, attr) for attr in attrs} -class TemperatureRecord(object): +class TemperatureRecord: RESERVED_IDENTIFIER_REGEX = re.compile("[0-9]+|[bc]") def __init__(self): @@ -376,7 +358,7 @@ class TemperatureRecord(object): def set_custom(self, identifier, actual=None, target=None): if self.RESERVED_IDENTIFIER_REGEX.match(identifier): - raise ValueError("{} is a reserved identifier".format(identifier)) + raise ValueError(f"{identifier} is a reserved identifier") current = self._custom.get(identifier, (None, None)) self._custom[identifier] = self._to_new_tuple(current, actual, target) @@ -433,7 +415,7 @@ class TemperatureRecord(object): return actual, target -class MachineCom(object): +class MachineCom: STATE_NONE = 0 STATE_OPEN_SERIAL = 1 STATE_DETECT_SERIAL = 2 @@ -894,7 +876,7 @@ class MachineCom(object): self._log(prefix + message) def _log(self, message): - message = to_unicode(message) + message = to_str(message) self._terminal_log.append(message) self._callback.on_comm_log(message) @@ -902,7 +884,7 @@ class MachineCom(object): def _to_logfile_with_terminal(self, message=None, level=logging.INFO): log = "Last lines in terminal:\n" + "\n".join( - map(lambda x: "| {}".format(x), list(self._terminal_log)) + map(lambda x: f"| {x}", list(self._terminal_log)) ) if message is not None: log = message + "\n| " + log @@ -975,7 +957,7 @@ class MachineCom(object): return "Offline after error" elif state == self.STATE_TRANSFERING_FILE: return "Transferring file to SD" - return "Unknown State ({})".format(self._state) + return f"Unknown State ({self._state})" def getErrorString(self): return self._errorValue @@ -1054,7 +1036,7 @@ class MachineCom(object): return None else: return ( - monotonic_time() + time.monotonic() - self._currentFile.getStartTime() - self._pauseWaitTimeLost ) @@ -1183,11 +1165,11 @@ class MachineCom(object): self.sendGcodeScript("beforePrinterDisconnected") if wait: if timeout is not None: - stop = monotonic_time() + timeout + stop = time.monotonic() + timeout while ( self._command_queue.unfinished_tasks or self._send_queue.unfinished_tasks - ) and monotonic_time() < stop: + ) and time.monotonic() < stop: time.sleep(0.1) else: self._command_queue.join() @@ -1252,7 +1234,7 @@ class MachineCom(object): tags=None, ): if not isinstance(cmd, QueueMarker): - cmd = to_unicode(cmd, errors="replace") + cmd = to_str(cmd, errors="replace") if not processed: cmd = process_gcode_line(cmd) if not cmd: @@ -1330,7 +1312,7 @@ class MachineCom(object): continue def to_list(data, t): - if isinstance(data, basestring): + if isinstance(data, str): data = list(s.strip() for s in data.split("\n")) if isinstance(data, (list, tuple)): @@ -1338,7 +1320,7 @@ class MachineCom(object): else: return None - additional_tags = {"plugin:{}".format(name)} + additional_tags = {f"plugin:{name}"} if len(retval) == 4: additional_tags |= set(retval[3]) @@ -1365,7 +1347,7 @@ class MachineCom(object): if ( isinstance(line, tuple) and len(line) == 2 - and isinstance(line[0], basestring) + and isinstance(line[0], str) and isinstance(line[1], set) ): tags = line[1] @@ -1389,20 +1371,20 @@ class MachineCom(object): tags_to_use = tags | { "trigger:comm.send_gcode_script", "source:script", - "script:{}".format(scriptName), + f"script:{scriptName}", } for line in scriptLines: # noinspection PyCompatibility if ( isinstance(line, tuple) and len(line) == 2 - and isinstance(line[0], basestring) + and isinstance(line[0], str) and isinstance(line[1], set) ): # 2-tuple: line + tags ttu = tags_to_use | line[1] line = line[0] - elif isinstance(line, basestring): + elif isinstance(line, str): # just a line ttu = tags_to_use else: @@ -1411,9 +1393,7 @@ class MachineCom(object): self.sendCommand(line, part_of_job=part_of_job, tags=ttu) - return "\n".join( - map(lambda x: x if isinstance(x, basestring) else x[0], scriptLines) - ) + return "\n".join(map(lambda x: x if isinstance(x, str) else x[0], scriptLines)) def startPrint(self, pos=None, tags=None, external_sd=False, user=None): if not self.isOperational() or self.isPrinting(): @@ -1422,7 +1402,7 @@ class MachineCom(object): if self._currentFile is None: raise ValueError("No file selected for printing") - self._heatupWaitStartTime = None if not self._heating else monotonic_time() + self._heatupWaitStartTime = None if not self._heating else time.monotonic() self._heatupWaitTimeLost = 0.0 self._pauseWaitStartTime = 0 self._pauseWaitTimeLost = 0.0 @@ -1437,7 +1417,7 @@ class MachineCom(object): "Starting job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Starting job on behalf of user {}".format(user)) + self._logger.info(f"Starting job on behalf of user {user}") try: with self._jobLock: @@ -1471,7 +1451,7 @@ class MachineCom(object): if pos is not None and isinstance(pos, int) and pos > 0: self._currentFile.pos = pos self.sendCommand( - "M26 S{}".format(pos), + f"M26 S{pos}", part_of_job=True, tags=tags | { @@ -1698,7 +1678,7 @@ class MachineCom(object): "Cancelling job on behalf of plugin {}".format(tag[7:]) ) elif "source:api" in tags: - self._logger.info("Cancelling job on behalf of user {}".format(user)) + self._logger.info(f"Cancelling job on behalf of user {user}") if self.isStreaming(): # we are streaming, we handle cancelling that differently... @@ -1848,7 +1828,7 @@ class MachineCom(object): "Pausing/resuming job on behalf of plugin {}".format(tag[7:]) ) elif user: - self._logger.info("Pausing/resuming job on behalf of user {}".format(user)) + self._logger.info(f"Pausing/resuming job on behalf of user {user}") valid_paused_states = (self.STATE_PAUSED, self.STATE_PAUSING) valid_running_states = ( @@ -1865,7 +1845,7 @@ class MachineCom(object): if not pause and self._state in valid_paused_states: if self._pauseWaitStartTime: self._pauseWaitTimeLost = self._pauseWaitTimeLost + ( - monotonic_time() - self._pauseWaitStartTime + time.monotonic() - self._pauseWaitStartTime ) self._pauseWaitStartTime = None @@ -1898,7 +1878,7 @@ class MachineCom(object): elif pause and self._state in valid_running_states: if not self._pauseWaitStartTime: - self._pauseWaitStartTime = monotonic_time() + self._pauseWaitStartTime = time.monotonic() self._changeState(self.STATE_PAUSING) if self.isSdFileSelected() and local_handling: @@ -2074,7 +2054,7 @@ class MachineCom(object): tags = set() self.sendCommand( - "M110 N{}".format(number), + f"M110 N{number}", part_of_job=part_of_job, tags=tags | { @@ -2121,7 +2101,7 @@ class MachineCom(object): return except Exception: self._logger.exception( - "Error while processing temperatures in {}, skipping".format(name), + f"Error while processing temperatures in {name}, skipping", extra={"plugin": name}, ) @@ -2226,7 +2206,7 @@ class MachineCom(object): if line is None: break - now = monotonic_time() + now = time.monotonic() if line.strip() != "": self._consecutive_timeouts = 0 @@ -2549,7 +2529,7 @@ class MachineCom(object): else: # multiple extruder coordinates provided, find current one self.last_position.e = ( - parsed.get("e{}".format(self._currentTool)) + parsed.get(f"e{self._currentTool}") if not self.isSdFileSelected() else None ) @@ -2604,7 +2584,7 @@ class MachineCom(object): ): self._logger.info("Externally triggered heatup detected") self._heating = True - self._heatupWaitStartTime = monotonic_time() + self._heatupWaitStartTime = time.monotonic() self._processTemperatures(line) self._callback.on_comm_temperature_update( @@ -2729,7 +2709,7 @@ class MachineCom(object): if not self._firmware_info_received and firmware_name: firmware_name = firmware_name.strip() self._logger.info( - 'Printer reports firmware name "{}"'.format(firmware_name) + f'Printer reports firmware name "{firmware_name}"' ) if self._firmware_detection: @@ -2854,7 +2834,7 @@ class MachineCom(object): # we actually do send a T command here instead of just settings self._currentTool just in case # we had any scripts or plugins modify stuff due to the prior tool change self.sendCommand( - "T{}".format(fallback_tool), + f"T{fallback_tool}", tags={ "trigger:revert_invalid_tool", }, @@ -3049,7 +3029,7 @@ class MachineCom(object): ### Serial detection if self._state == self.STATE_DETECT_SERIAL: - if line == "" or monotonic_time() > self._ok_timeout: + if line == "" or time.monotonic() > self._ok_timeout: self._perform_detection_step() elif "start" in line or line.startswith("ok"): self._onConnected() @@ -3066,7 +3046,7 @@ class MachineCom(object): # if it was a wait we probably missed an ok, so let's simulate that now self._handle_ok() self._onConnected() - elif monotonic_time() > self._timeout: + elif time.monotonic() > self._timeout: if try_hello and self._hello_sent < 3: self._log( "No answer from the printer within the connection timeout, trying another hello" @@ -3178,9 +3158,7 @@ class MachineCom(object): # now increment the timeout counter self._consecutive_timeouts += 1 - self._logger.debug( - "Now at {} consecutive timeouts".format(self._consecutive_timeouts) - ) + self._logger.debug(f"Now at {self._consecutive_timeouts} consecutive timeouts") if 0 < consecutive_max < self._consecutive_timeouts: # too many consecutive timeouts, we give up @@ -3237,7 +3215,7 @@ class MachineCom(object): def _perform_detection_step(self, init=False): def log(message): self._log(message) - self._logger.info("Serial detection: {}".format(message)) + self._logger.info(f"Serial detection: {message}") if init: port = self._port @@ -3287,7 +3265,7 @@ class MachineCom(object): try: if self._serial.timeout != timeout: self._serial.timeout = timeout - self._timeout = self._ok_timeout = monotonic_time() + timeout + self._timeout = self._ok_timeout = time.monotonic() + timeout except Exception: self._log( "Unexpected error while setting timeout {}: {}".format( @@ -3295,7 +3273,7 @@ class MachineCom(object): ) ) self._logger.exception( - "Unexpected error while setting timeout {}".format(timeout) + f"Unexpected error while setting timeout {timeout}" ) else: self._do_send_without_checksum(b"", log=False) # new line to reset things @@ -3324,7 +3302,7 @@ class MachineCom(object): (p, b) = self._detection_candidates.pop(0) try: - log("Trying port {}, baudrate {}".format(p, b)) + log(f"Trying port {p}, baudrate {b}") if self._serial is None or self._serial.port != p: if not self._open_serial(p, b, trigger_errors=False): log( @@ -3347,9 +3325,7 @@ class MachineCom(object): b, get_exception_string() ) ) - self._logger.exception( - "Unexpected error while setting baudrate {}".format(b) - ) + self._logger.exception(f"Unexpected error while setting baudrate {b}") error_text = "No more candidates to test, and no working port/baudrate combination detected." self._trigger_error(error_text, "autodetect") @@ -3358,7 +3334,7 @@ class MachineCom(object): if self._heating: if self._heatupWaitStartTime: self._heatupWaitTimeLost = self._heatupWaitTimeLost + ( - monotonic_time() - self._heatupWaitStartTime + time.monotonic() - self._heatupWaitStartTime ) self._heatupWaitStartTime = None self._heating = False @@ -3509,7 +3485,7 @@ class MachineCom(object): except Exception: interval = 2 self.sendCommand( - "M155 S{}".format(interval), + f"M155 S{interval}", tags={"trigger:comm.set_autoreport_temperature_interval"}, ) @@ -3520,7 +3496,7 @@ class MachineCom(object): except Exception: interval = 1 self.sendCommand( - "M27 S{}".format(interval), + f"M27 S{interval}", tags={"trigger:comm.set_autoreport_sdstatus_interval"}, ) @@ -3533,7 +3509,7 @@ class MachineCom(object): except Exception: interval = 5 self.sendCommand( - "M154 S{}".format(interval), + f"M154 S{interval}", part_of_job=part_of_job, tags=tags | {"trigger:comm.set_autoreport_pos_interval"}, ) @@ -3547,7 +3523,7 @@ class MachineCom(object): except Exception: interval = 2 self.sendCommand( - "M113 S{}".format(interval), + f"M113 S{interval}", tags={"trigger:comm.set_busy_protocol_interval"}, on_sent=callback, ) @@ -3680,7 +3656,7 @@ class MachineCom(object): return max(comm_timeout, temperature_timeout + 1) def _get_new_communication_timeout(self): - return monotonic_time() + self._get_communication_timeout_interval() + return time.monotonic() + self._get_communication_timeout_interval() def _send_from_command_queue(self): # We loop here to make sure that if we do NOT send the first command @@ -3721,7 +3697,7 @@ class MachineCom(object): def default(_, p, b, timeout): # connect to regular serial port self._dual_log( - "Connecting to port {}, baudrate {}".format(port, baudrate), + f"Connecting to port {port}, baudrate {baudrate}", level=logging.INFO, ) @@ -3974,8 +3950,8 @@ class MachineCom(object): try: self._log("Recv: {}".format(sanitize_ascii(ret))) except ValueError as e: - self._log("WARN: While reading last line: {}".format(e)) - self._log("Recv: {!r}".format(ret)) + self._log(f"WARN: While reading last line: {e}") + self._log(f"Recv: {ret!r}") if null_pos >= 0: self._logger.warning("Received line:") @@ -4007,7 +3983,7 @@ class MachineCom(object): 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." @@ -4058,8 +4034,8 @@ class MachineCom(object): line, tags={ "source:file", - "filepos:{}".format(pos), - "fileline:{}".format(lineno), + f"filepos:{pos}", + f"fileline:{lineno}", }, ) self._callback.on_comm_progress() @@ -4167,7 +4143,7 @@ class MachineCom(object): # # this it to prevent the log from getting flooded for extremely bad communication issues if self._log_resends: - now = monotonic_time() + now = time.monotonic() new_rate_window = ( self._log_resends_rate_start is None or self._log_resends_rate_start + self._log_resends_rate_frame < now @@ -4447,7 +4423,7 @@ class MachineCom(object): break # sleep if we are dwelling - now = monotonic_time() + now = time.monotonic() if ( self._blockWhileDwelling and self._dwelling_until @@ -4564,8 +4540,8 @@ class MachineCom(object): def _log_command_phase(self, phase, command, *args, **kwargs): if self._phaseLogger.isEnabledFor(logging.DEBUG): output_parts = [ - "phase: {}".format(phase), - "command: {}".format(to_unicode(command, errors="replace")), + f"phase: {phase}", + "command: {}".format(to_str(command, errors="replace")), ] if kwargs.get("command_type"): @@ -4629,8 +4605,8 @@ class MachineCom(object): hook_results, tags_to_add={ "source:rewrite", - "phase:{}".format(phase), - "plugin:{}".format(name), + f"phase:{phase}", + f"plugin:{name}", }, ) @@ -4644,7 +4620,7 @@ class MachineCom(object): "command as-is.".format( name=name, phase=phase, - command=to_unicode(command, errors="replace"), + command=to_str(command, errors="replace"), ), extra={"plugin": name}, ) @@ -4740,20 +4716,20 @@ class MachineCom(object): self._logger.exception( "Error while processing hook {} for " "phase {} and command {}:".format( - name, phase, to_unicode(atcommand, errors="replace") + name, phase, to_str(atcommand, errors="replace") ), extra={"plugin": name}, ) # trigger built-in handler if available - handler = getattr(self, "_atcommand_{}_{}".format(atcommand, phase), None) + handler = getattr(self, f"_atcommand_{atcommand}_{phase}", None) if callable(handler): try: handler(atcommand, parameters, tags=tags) except Exception: self._logger.exception( "Error in handler for phase {} and command {}".format( - phase, to_unicode(atcommand, errors="replace") + phase, to_str(atcommand, errors="replace") ) ) @@ -4930,7 +4906,7 @@ class MachineCom(object): # noinspection PyCompatibility if isinstance(d, tuple) and len(d) == 2: result.append((d[0], None, d[1])) - elif isinstance(d, basestring): + elif isinstance(d, str): result.append(d) return result @@ -5080,7 +5056,7 @@ class MachineCom(object): wait=False, support_r=False, *args, - **kwargs + **kwargs, ): toolNum = self._currentTool toolMatch = regexes_parameters["intT"].search(cmd) @@ -5118,7 +5094,7 @@ class MachineCom(object): wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -5146,7 +5122,7 @@ class MachineCom(object): wait=False, support_r=False, *args, - **kwargs + **kwargs, ): match = regexes_parameters["floatS"].search(cmd) if not match and support_r: @@ -5168,7 +5144,7 @@ class MachineCom(object): def _gcode_M109_sent( self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs ): - self._heatupWaitStartTime = monotonic_time() + self._heatupWaitStartTime = time.monotonic() self._long_running_command = True self._heating = True self._gcode_M104_sent(cmd, cmd_type, wait=True, support_r=True) @@ -5176,7 +5152,7 @@ class MachineCom(object): def _gcode_M190_sent( self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs ): - self._heatupWaitStartTime = monotonic_time() + self._heatupWaitStartTime = time.monotonic() self._long_running_command = True self._heating = True self._gcode_M140_sent(cmd, cmd_type, wait=True, support_r=True) @@ -5184,7 +5160,7 @@ class MachineCom(object): def _gcode_M191_sent( self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs ): - self._heatupWaitStartTime = monotonic_time() + self._heatupWaitStartTime = time.monotonic() self._long_running_command = True self._heating = True self._gcode_M141_sent(cmd, cmd_type, wait=True, support_r=True) @@ -5192,7 +5168,7 @@ class MachineCom(object): def _gcode_M116_sent( self, cmd, cmd_type=None, gcode=None, subcode=None, *args, **kwargs ): - self._heatupWaitStartTime = monotonic_time() + self._heatupWaitStartTime = time.monotonic() self._long_running_command = True self._heating = True @@ -5246,7 +5222,7 @@ class MachineCom(object): with self._line_mutex: self._logger.info( - "M110 detected, setting current line number to {}".format(newLineNumber) + f"M110 detected, setting current line number to {newLineNumber}" ) # send M110 command with new line number @@ -5274,9 +5250,7 @@ class MachineCom(object): for tool in range( self._printerProfileManager.get_current_or_default()["extruder"]["count"] ): - self._do_increment_and_send_with_checksum( - "M104 T{tool} S0".format(tool=tool).encode("ascii") - ) + self._do_increment_and_send_with_checksum(f"M104 T{tool} S0".encode("ascii")) if self._printerProfileManager.get_current_or_default()["heatedBed"]: self._do_increment_and_send_with_checksum(b"M140 S0") @@ -5316,7 +5290,7 @@ class MachineCom(object): _timeout = float(s_match.group("value")) self._timeout = self._get_new_communication_timeout() + _timeout - self._dwelling_until = monotonic_time() + _timeout + self._dwelling_until = time.monotonic() + _timeout def _emergency_force_send(self, cmd, message, gcode=None, *args, **kwargs): # only jump the queue with our command if the EMERGENCY_PARSER capability is available @@ -5381,10 +5355,10 @@ class MachineCom(object): if gcode in self._emergency_commands and gcode != "M112": return self._emergency_force_send( cmd, - "Force-sending {} to the printer".format(gcode), + f"Force-sending {gcode} to the printer", gcode=gcode, *args, - **kwargs + **kwargs, ) if ( @@ -5393,7 +5367,7 @@ class MachineCom(object): and "trigger:cancel" not in tags and "trigger:pause" not in tags ): - self._logger.info("Pausing print job due to command {}".format(gcode)) + self._logger.info(f"Pausing print job due to command {gcode}") self.setPause(True) if gcode in self._blocked_commands: @@ -5442,7 +5416,7 @@ class MachineCom(object): ### MachineCom callback ################################################################################################ -class MachineComPrintCallback(object): +class MachineComPrintCallback: def on_comm_log(self, message): pass @@ -5518,7 +5492,7 @@ class MachineComPrintCallback(object): ### Printing file information classes ################################################################################## -class PrintingFileInformation(object): +class PrintingFileInformation: """ Encapsulates information regarding the current file being printed: file name, current position, total size and time the print started. @@ -5574,7 +5548,7 @@ class PrintingFileInformation(object): """ Marks the print job as started and remembers the start time. """ - self._start_time = monotonic_time() + self._start_time = time.monotonic() self._done = False def close(self): @@ -5641,7 +5615,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 @@ -5662,7 +5636,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): PrintingFileInformation.start(self) with self._handle_mutex: bom = get_bom(self._filename, encoding="utf-8-sig") - self._handle = io.open( + self._handle = open( self._filename, encoding="utf-8-sig", errors="replace", newline="" ) self._pos = self._handle.tell() @@ -5693,9 +5667,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation): """ with self._handle_mutex: if self._handle is None: - self._logger.warning( - "File {} is not open for reading".format(self._filename) - ) + self._logger.warning(f"File {self._filename} is not open for reading") return None, None, None try: @@ -5740,8 +5712,8 @@ class PrintingGcodeFileInformation(PrintingFileInformation): return process_gcode_line(line, offsets=offsets, current_tool=current_tool) def _report_stats(self): - duration = monotonic_time() - self._start_time - self._logger.info("Finished in {:.3f} s.".format(duration)) + duration = time.monotonic() - self._start_time + self._logger.info(f"Finished in {duration:.3f} s.") pass @@ -5753,7 +5725,7 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation): def start(self): PrintingGcodeFileInformation.start(self) - self._start_time = monotonic_time() + self._start_time = time.monotonic() def getLocalFilename(self): return self._localFilename @@ -5765,7 +5737,7 @@ class StreamingGcodeFileInformation(PrintingGcodeFileInformation): return process_gcode_line(line) def _report_stats(self): - duration = monotonic_time() - self._start_time + duration = time.monotonic() - self._start_time read_lines = self._read_lines if duration > 0 and read_lines > 0: stats = { @@ -5909,7 +5881,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -5926,7 +5898,7 @@ class SendQueue(PrependableQueue): if item_type is not None: if item_type in self._lookup: raise TypeAlreadyInQueue( - item_type, "Type {} is already in queue".format(item_type) + item_type, f"Type {item_type} is already in queue" ) else: self._lookup.add(item_type) @@ -6057,11 +6029,7 @@ def convert_pause_triggers(configured_triggers): for t in triggers.keys(): if len(triggers[t]) > 0: result[t] = re.compile( - "|".join( - map( - lambda pattern: "({pattern})".format(pattern=pattern), triggers[t] - ) - ) + "|".join(map(lambda pattern: f"({pattern})", triggers[t])) ) return result @@ -6441,31 +6409,31 @@ def _normalize_command_handler_result( be empty in which case the command is to be suppressed. Examples: - >>> _normalize_command_handler_result("M105", None, "M105", None, None, None) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, None) [('M105', None, 'M105', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110") # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, "M110") [('M110', None, 'M110', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110"]) [('M110', None, 'M110', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", "M117 Foobar"]) [('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), "M117 Foobar"]) [('M110', None, 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110", "lineno_reset"), "M117 Foobar"]) [('M110', 'lineno_reset', 'M110', None, None), ('M117 Foobar', None, 'M117', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, []) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, []) [] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, ["M110", None]) [('M110', None, 'M110', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), (None, "ignored")]) [('M110', None, 'M110', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, None, [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) [('M110', None, 'M110', None, None), ('M117 Foobar', 'display_message', 'M117', None, None), ('M110', 'lineno_reset', 'M110', None, None)] - >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M117 Foobar"]) [('M110', None, 'M110', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2'})] - >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", "M105", "M117 Foobar"], tags_to_add={"tag3"}) [('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', None, 'M105', None, {'tag1', 'tag2'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})] - >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE + >>> _normalize_command_handler_result("M105", None, "M105", None, {"tag1", "tag2"}, ["M110", ("M105", "temperature_poll"), "M117 Foobar"], tags_to_add={"tag3"}) [('M110', None, 'M110', None, {'tag1', 'tag2', 'tag3'}), ('M105', 'temperature_poll', 'M105', None, {'tag1', 'tag2', 'tag3'}), ('M117 Foobar', None, 'M117', None, {'tag1', 'tag2', 'tag3'})] Arguments: @@ -6514,7 +6482,7 @@ def _normalize_command_handler_result( # copy the tags tags = set(tags) - if isinstance(handler_result, basestring): + if isinstance(handler_result, str): # entry is just a string, replace command with it command = handler_result @@ -6579,7 +6547,7 @@ def _normalize_command_handler_result( return result -class QueueMarker(object): +class QueueMarker: def __init__(self, callback): self.callback = callback @@ -6678,14 +6646,12 @@ def upload_cli(): def on_comm_file_transfer_started(self, filename, filesize, user=None): # transfer started, report - _logger.info( - "Started file transfer of {}, size {}B".format(filename, filesize) - ) + _logger.info(f"Started file transfer of {filename}, size {filesize}B") self.started = True def on_comm_file_transfer_done(self, filename): # transfer done, report, print stats and finish - _logger.info("Finished file transfer of {}".format(filename)) + _logger.info(f"Finished file transfer of {filename}") self.finished.set() def on_comm_state_change(self, state): diff --git a/src/octoprint/util/commandline.py b/src/octoprint/util/commandline.py index 24e17bd9d..96bca85a8 100644 --- a/src/octoprint/util/commandline.py +++ b/src/octoprint/util/commandline.py @@ -1,28 +1,18 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 logging +import queue import re import time import sarge -from past.builtins import unicode +from octoprint.util import to_str 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 - # These regexes are based on the colorama package # Author: Jonathan Hartley # License: BSD-3 (https://github.com/tartley/colorama/blob/master/LICENSE.txt) @@ -39,10 +29,10 @@ def clean_ansi(line): Removes ANSI control codes from ``line``. Parameters: - line (bytes or unicode): the line to process + line (bytes or str): the line to process Returns: - (bytes or unicode) The line without any ANSI control codes + (bytes or str) The line without any ANSI control codes Example:: @@ -53,7 +43,7 @@ def clean_ansi(line): >>> clean_ansi(text) # doctest: +ALLOW_BYTES 'We hide the cursor here and then show it again here' """ - if isinstance(line, unicode): + if isinstance(line, str): return _ANSI_REGEX.sub(b"", line.encode("latin1")).decode("latin1") return _ANSI_REGEX.sub(b"", line) @@ -74,7 +64,7 @@ class CommandlineError(Exception): self.stderr = stderr -class CommandlineCaller(object): +class CommandlineCaller: """ The CommandlineCaller is a utility class that allows running command line commands while logging their stdout and stderr via configurable callback functions. @@ -171,15 +161,9 @@ class CommandlineCaller(object): joined_command = " ".join(command) else: joined_command = command - self._logger.debug("Calling: {}".format(joined_command)) + self._logger.debug(f"Calling: {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"] = { - to_native_str(k): to_native_str(v) for k, v in kwargs["env"].items() - } - delimiter = kwargs.get("delimiter", b"\n") try: kwargs.pop("delimiter") @@ -215,9 +199,7 @@ class CommandlineCaller(object): if not p.commands[0].process: # the process might have been set to None in case of any exception - self._logger.error( - "Error while trying to run command {}".format(joined_command) - ) + self._logger.error(f"Error while trying to run command {joined_command}") return None, [], [] all_stdout = [] @@ -227,7 +209,7 @@ class CommandlineCaller(object): if not lines: return [] processed = self._preprocess_lines( - *map(lambda x: to_unicode(x, errors="replace"), lines) + *map(lambda x: to_str(x, errors="replace"), lines) ) logger(*processed) return list(processed) diff --git a/src/octoprint/util/connectivity.py b/src/octoprint/util/connectivity.py index a46c41d2e..eaa39267c 100644 --- a/src/octoprint/util/connectivity.py +++ b/src/octoprint/util/connectivity.py @@ -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" @@ -12,7 +9,7 @@ import time from octoprint.util.net import resolve_host, server_reachable -class ConnectivityChecker(object): +class ConnectivityChecker: """ Regularly checks for online connectivity. @@ -171,7 +168,7 @@ class ConnectivityChecker(object): "online": self.online, "enabled": self.enabled, "connection_ok": self._connection_working, - "connection_check": "{}:{}".format(self._host, self._port), + "connection_check": f"{self._host}:{self._port}", } if self._name: result.update( @@ -211,9 +208,7 @@ class ConnectivityChecker(object): if self._name: if connection_working: - self._logger.debug( - "Checking if we can resolve {}...".format(self._name) - ) + self._logger.debug(f"Checking if we can resolve {self._name}...") resolution_working = len(resolve_host(self._name)) > 0 else: resolution_working = False diff --git a/src/octoprint/util/dev.py b/src/octoprint/util/dev.py index 6b85493bd..dd8f599aa 100644 --- a/src/octoprint/util/dev.py +++ b/src/octoprint/util/dev.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This module provides a bunch of utility methods and helpers FOR DEVELOPMENT ONLY. """ @@ -8,6 +5,7 @@ This module provides a bunch of utility methods and helpers FOR DEVELOPMENT ONLY __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" import contextlib +import time @contextlib.contextmanager @@ -29,13 +27,11 @@ def duration_log(context=None, log=None): log = logging.getLogger(__name__).debug - import octoprint.util - - start = octoprint.util.monotonic_time() + start = time.monotonic() try: yield finally: - end = octoprint.util.monotonic_time() + end = time.monotonic() duration = end - start if context: @@ -70,7 +66,7 @@ def log_duration(log=None, with_args=False): arguments = "".join([args_str, sep, kwargs_str]) else: arguments = "..." - context = "{name}({arguments})".format(name=f.__name__, arguments=arguments) + context = f"{f.__name__}({arguments})" with duration_log(context=context, log=log): return f(*args, **kwargs) diff --git a/src/octoprint/util/files.py b/src/octoprint/util/files.py index 49a6efb28..567165500 100644 --- a/src/octoprint/util/files.py +++ b/src/octoprint/util/files.py @@ -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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -15,7 +12,7 @@ def _sfn_really_universal(name): ### taken from pathvalidate library _WINDOWS_RESERVED_FILE_NAMES = ("CON", "PRN", "AUX", "CLOCK$", "NUL") + tuple( - "{:s}{:d}".format(name, num) + f"{name:s}{num:d}" for name, num in itertools.product(("COM", "LPT"), range(1, 10)) ) _MACOS_RESERVED_FILE_NAMES = (":",) @@ -31,27 +28,28 @@ def sanitize_filename(name, really_universal=False): """ Sanitizes the provided filename. Implementation differs between Python versions. - On Python 2, the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with - safe chars ``-_.()[] `` and all spaces replaced by ``_``. - - On Python 3, ``pathvalidate.sanitize_filename`` will be used instead, leaving the + Under normal operation, ``pathvalidate.sanitize_filename`` will be used, leaving the name as intact as possible while still being a legal file name under all operating systems. + Behaviour can be changed by setting ``really_universal`` to ``True``. In this case, + the name will be ASCII-fied, using ``octoprint.util.text.sanitize`` with + safe chars ``-_.()[] `` and all spaces replaced by ``_``. This is the old behaviour. + In all cases, a single leading ``.`` will be removed (as it denotes hidden files on *nix). Args: name: The file name to sanitize. Only the name, no path elements. - really_universal: If ``True``, the Python 2 method of sanitization will always + really_universal: If ``True``, the old method of sanitization will always be used. Defaults to ``False``. Returns: the sanitized file name """ - from octoprint.util import to_unicode + from octoprint.util import to_str - name = to_unicode(name) + name = to_str(name) if name is None: return None @@ -59,10 +57,7 @@ def sanitize_filename(name, really_universal=False): if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - try: - from pathvalidate import sanitize_filename as sfn - except ImportError: - sfn = _sfn_really_universal + from pathvalidate import sanitize_filename as sfn if really_universal: result = _sfn_really_universal(name) @@ -101,24 +96,24 @@ def get_dos_filename( Examples: - >>> get_dos_filename("test1234.gco") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("test1234.gco") 'test1234.gco' - >>> get_dos_filename("test1234.gcode") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("test1234.gcode") 'test1234.gco' - >>> get_dos_filename("test12345.gco") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("test12345.gco") 'test12~1.gco' - >>> get_dos_filename("Wölfe 🐺.gcode") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("Wölfe 🐺.gcode") 'wolfe_~1.gco' - >>> get_dos_filename("💚.gcode") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("💚.gcode") 'green_~1.gco' - >>> get_dos_filename("test1234.fnord", extension="gco") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("test1234.fnord", extension="gco") 'test1234.gco' - >>> get_dos_filename("auto0.g", extension="gco") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("auto0.g", extension="gco") 'auto0.gco' - >>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) # doctest: +ALLOW_UNICODE + >>> get_dos_filename("auto0.g", extension="gco", whitelisted_extensions=["g"]) 'auto0.g' >>> get_dos_filename(None) - >>> get_dos_filename("foo") # doctest: +ALLOW_UNICODE + >>> get_dos_filename("foo") 'foo' """ @@ -192,42 +187,42 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power= Examples: - >>> find_collision_free_name("test1234", "gco", []) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test1234", "gco", []) 'test1234.gco' - >>> find_collision_free_name("test1234", "gcode", []) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test1234", "gcode", []) 'test1234.gco' - >>> find_collision_free_name("test12345", "gco", []) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", []) 'test12~1.gco' - >>> find_collision_free_name("test 123", "gco", []) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test 123", "gco", []) 'test_123.gco' - >>> find_collision_free_name("test1234", "g o", []) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test1234", "g o", []) 'test1234.g_o' - >>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", ["/test12~1.gco"]) 'test12~2.gco' >>> many_files = ["/test12~{}.gco".format(x) for x in range(10)[1:]] - >>> find_collision_free_name("test12345", "gco", many_files) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", many_files) 'test1~10.gco' >>> many_more_files = many_files + ["/test1~{}.gco".format(x) for x in range(10, 99)] - >>> find_collision_free_name("test12345", "gco", many_more_files) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", many_more_files) 'test1~99.gco' >>> many_more_files_plus_one = many_more_files + ["/test1~99.gco"] - >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one) Traceback (most recent call last): ... ValueError: Can't create a collision free filename - >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) # doctest: +ALLOW_UNICODE + >>> find_collision_free_name("test12345", "gco", many_more_files_plus_one, max_power=3) 'test~100.gco' """ - from octoprint.util import to_unicode + from octoprint.util import to_str - filename = to_unicode(filename) - extension = to_unicode(extension) + filename = to_str(filename) + extension = to_str(extension) if filename.startswith("/"): filename = filename[1:] existing_filenames = [ - to_unicode(x[1:] if x.startswith("/") else x) for x in existing_filenames + to_str(x[1:] if x.startswith("/") else x) for x in existing_filenames ] def make_valid(text): diff --git a/src/octoprint/util/fixes.py b/src/octoprint/util/fixes.py index d369556f9..a52838227 100644 --- a/src/octoprint/util/fixes.py +++ b/src/octoprint/util/fixes.py @@ -1,47 +1,5 @@ -# -*- coding: utf-8 -*- """ This module contains a functions that monkey patch third party dependencies in the one or other way. """ -from __future__ import absolute_import, division, print_function, unicode_literals __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" - -import functools -import sys -import warnings - - -def patch_sarge_async_on_py2(): - if sys.version_info[0] >= 3: - return - - def move_async(f): - @functools.wraps(f) - def decorated_function(*args, **kwargs): - if "async" in kwargs: - warnings.warn( - 'sarge\'s "async" parameter is deprecated. Use "_async" instead.', - DeprecationWarning, - stacklevel=2, - ) - kwargs["async_"] = kwargs.pop("async") - return f(*args, **kwargs) - - return decorated_function - - import sarge - - # wrap helper - sarge.run = move_async(sarge.run) - - # wrap Command - sarge.Command.run = move_async(sarge.Command.run) - - # wrap Pipeline - sarge.Pipeline.run = move_async(sarge.Pipeline.run) - sarge.Pipeline.run_command_node = move_async(sarge.Pipeline.run_command_node) - sarge.Pipeline.run_list_node = move_async(sarge.Pipeline.run_list_node) - sarge.Pipeline.run_logical_node = move_async(sarge.Pipeline.run_logical_node) - sarge.Pipeline.run_node = move_async(sarge.Pipeline.run_node) - sarge.Pipeline.run_node_in_thread = move_async(sarge.Pipeline.run_node_in_thread) - sarge.Pipeline.run_pipeline_node = move_async(sarge.Pipeline.run_pipeline_node) diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py index 77640ef65..af30cb260 100644 --- a/src/octoprint/util/gcodeInterpreter.py +++ b/src/octoprint/util/gcodeInterpreter.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge based on work by David Braam" __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2013 David Braam, Gina Häußge - Released under terms of the AGPLv3 License" @@ -16,7 +13,7 @@ import re import zlib -class Vector3D(object): +class Vector3D: """ 3D vector value @@ -126,7 +123,7 @@ class Vector3D(object): ) -class MinMax3D(object): +class MinMax3D: """ Tracks minimum and maximum of recorded values @@ -210,7 +207,7 @@ regex_command = re.compile( """Regex for a GCODE command.""" -class gcode(object): +class gcode: def __init__(self, incl_layers=False, progress_callback=None): self._logger = logging.getLogger(__name__) self.extrusionAmount = [0] diff --git a/src/octoprint/util/jinja.py b/src/octoprint/util/jinja.py index 97b839603..aa7600d7e 100644 --- a/src/octoprint/util/jinja.py +++ b/src/octoprint/util/jinja.py @@ -1,17 +1,9 @@ -# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import logging import os -try: - from os import scandir, walk -except ImportError: - from scandir import scandir, walk # noqa: F401 - from jinja2 import nodes from jinja2.ext import Extension from jinja2.loaders import ( @@ -156,7 +148,7 @@ class WarningLoader(BaseLoader): def get_all_template_paths(loader): def walk_folder(folder): files = [] - walk_dir = walk(folder, followlinks=True) + walk_dir = os.walk(folder, followlinks=True) for dirpath, _, filenames in walk_dir: for filename in filenames: path = os.path.join(dirpath, filename) @@ -228,7 +220,7 @@ class ExceptionHandlerExtension(Extension): tags = {"try"} def __init__(self, environment): - super(ExceptionHandlerExtension, self).__init__(environment) + super().__init__(environment) self._logger = logging.getLogger(__name__) def parse(self, parser): @@ -291,7 +283,7 @@ class ExceptionHandlerExtension(Extension): trycatch = ExceptionHandlerExtension -class MarkdownFilter(object): +class MarkdownFilter: def __init__(self, app, **markdown_options): self._markdown_options = markdown_options app.jinja_env.filters.setdefault("markdown", self) diff --git a/src/octoprint/util/json/__init__.py b/src/octoprint/util/json/__init__.py index 4fe7be597..244adb6c1 100644 --- a/src/octoprint/util/json/__init__.py +++ b/src/octoprint/util/json/__init__.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -10,7 +7,7 @@ import json from frozendict import frozendict -from octoprint.util import to_unicode +from octoprint.util import to_str def dump(obj): @@ -22,7 +19,7 @@ def dump(obj): ) -class JsonEncoding(object): +class JsonEncoding: encoders = collections.OrderedDict() @@ -46,4 +43,4 @@ class JsonEncoding(object): JsonEncoding.add_encoder(frozendict, lambda obj: dict(obj)) -JsonEncoding.add_encoder(bytes, lambda obj: to_unicode(obj)) +JsonEncoding.add_encoder(bytes, lambda obj: to_str(obj)) diff --git a/src/octoprint/util/net.py b/src/octoprint/util/net.py index 124854774..6c04451b8 100644 --- a/src/octoprint/util/net.py +++ b/src/octoprint/util/net.py @@ -1,10 +1,6 @@ -# -*- 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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import logging import os import socket @@ -45,7 +41,7 @@ if hasattr(socket, "IPPROTO_IPV6") and hasattr(socket, "IPV6_V6ONLY"): 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 + # Python on Windows lacks IPPROTO_IPV6, but supports the socket options just fine, let's redefine it IPPROTO_IPV6 = 41 IPV6_V6ONLY = 27 else: @@ -66,7 +62,7 @@ def get_lan_ranges(additional_private=None): _, prefix = prefix.split("/") addr = strip_interface_tag(address["addr"]) - return netaddr.IPNetwork("{}/{}".format(addr, prefix)) + return netaddr.IPNetwork(f"{addr}/{prefix}") subnets = [] @@ -253,10 +249,10 @@ def server_reachable(host, port, timeout=3.05, proto="tcp", source=None): def resolve_host(host): import socket - from octoprint.util import to_unicode + from octoprint.util import to_str try: - return [to_unicode(x[4][0]) for x in socket.getaddrinfo(host, 80)] + return [to_str(x[4][0]) for x in socket.getaddrinfo(host, 80)] except Exception: return [] @@ -281,7 +277,7 @@ def download_file(url, folder, max_length=None): path = os.path.abspath(os.path.join(folder, filename)) assert path.startswith(folder) - with io.open(path, "wb") as f: + with open(path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return path diff --git a/src/octoprint/util/paths.py b/src/octoprint/util/paths.py index f69de2333..41a54fe76 100644 --- a/src/octoprint/util/paths.py +++ b/src/octoprint/util/paths.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/src/octoprint/util/pip.py b/src/octoprint/util/pip.py index a04122a4f..a4500a1cf 100644 --- a/src/octoprint/util/pip.py +++ b/src/octoprint/util/pip.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -15,7 +12,7 @@ import threading import pkg_resources import sarge -from octoprint.util import to_unicode +from octoprint.util import to_str from octoprint.util.platform import CLOSE_FDS from .commandline import CommandlineCaller, clean_ansi @@ -190,9 +187,7 @@ class PipCaller(CommandlineCaller): # add --no-use-wheel for versions that otherwise break if pip_version in cls.no_use_wheel and "--no-use-wheel" not in args: - logger.debug( - "Version {} needs --no-use-wheel to properly work.".format(pip_version) - ) + logger.debug(f"Version {pip_version} needs --no-use-wheel to properly work.") args.append("--no-use-wheel") # remove --user if it's present and a virtual env is detected @@ -451,7 +446,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["version"]: self._logger.debug( - "Using cached pip version information for {}".format(pip_command_str) + f"Using cached pip version information for {pip_command_str}" ) return _cache["version"][pip_command_str] @@ -465,7 +460,7 @@ class PipCaller(CommandlineCaller): if p.returncode != 0: self._logger.warning( - "Error while trying to run pip --version: {}".format(p.stderr.text) + f"Error while trying to run pip --version: {p.stderr.text}" ) return None, None @@ -501,7 +496,7 @@ class PipCaller(CommandlineCaller): ) return None, None - self._logger.info("Version of pip is {}".format(version_segment)) + self._logger.info(f"Version of pip is {version_segment}") result = pip_version, version_segment _cache["version"][pip_command_str] = result @@ -515,7 +510,7 @@ class PipCaller(CommandlineCaller): with _cache_mutex: if not self.ignore_cache and pip_command_str in _cache["setup"]: self._logger.debug( - "Using cached pip setup information for {}".format(pip_command_str) + f"Using cached pip setup information for {pip_command_str}" ) return _cache["setup"][pip_command_str] @@ -626,10 +621,10 @@ class PipCaller(CommandlineCaller): Example:: >>> text = b'some text with some\x1b[?25h ANSI codes for \x1b[31mred words\x1b[39m and\x1b[?25l also some cursor control codes' - >>> PipCaller._preprocess(text) # doctest: +ALLOW_UNICODE + >>> PipCaller._preprocess(text) 'some text with some ANSI codes for red words and also some cursor control codes' """ - return to_unicode(clean_ansi(text)) + return to_str(clean_ansi(text)) class LocalPipCaller(PipCaller): diff --git a/src/octoprint/util/piptestballoon/setup.py b/src/octoprint/util/piptestballoon/setup.py index 58dc094a1..c0e26335d 100644 --- a/src/octoprint/util/piptestballoon/setup.py +++ b/src/octoprint/util/piptestballoon/setup.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This "python package" doesn't actually install. This is intentional. It is merely used to figure out some information about the environment a specific pip call @@ -29,9 +26,9 @@ virtual_env = hasattr(sys, "real_prefix") or ( writable = os.access(install_dir, os.W_OK) lines = [ - "PIP_INSTALL_DIR={}".format(install_dir), - "PIP_VIRTUAL_ENV={}".format(virtual_env), - "PIP_WRITABLE={}".format(writable), + f"PIP_INSTALL_DIR={install_dir}", + f"PIP_VIRTUAL_ENV={virtual_env}", + f"PIP_WRITABLE={writable}", ] # write to stdout diff --git a/src/octoprint/util/platform/__init__.py b/src/octoprint/util/platform/__init__.py index 3613bd9bf..72352d08a 100644 --- a/src/octoprint/util/platform/__init__.py +++ b/src/octoprint/util/platform/__init__.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- """ This module bundles platform specific flags and implementations. """ -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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" @@ -62,15 +60,9 @@ CLOSE_FDS = True Default setting for close_fds parameter to Popen/sarge.run. Set ``close_fds`` on every sub process to this to ensure file handlers will be closed -on child processes on platforms that support this (anything Python 3.7+ or anything -but win32 in earlier Python versions). +on child processes on platforms. """ -if sys.platform == "win32" and sys.version_info < (3, 7): - # close_fds=True is only supported on win32 with enabled stdout/stderr - # capturing starting with Python 3.7 - CLOSE_FDS = False - # current os _OPERATING_SYSTEMS = { diff --git a/src/octoprint/util/text.py b/src/octoprint/util/text.py index 41026a18c..d82f47b41 100644 --- a/src/octoprint/util/text.py +++ b/src/octoprint/util/text.py @@ -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" @@ -8,7 +5,7 @@ import re from emoji import demojize -from octoprint.util import to_unicode +from octoprint.util import to_str from octoprint.vendor.awesome_slugify import Slugify _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) @@ -16,7 +13,7 @@ _SLUGIFIES = {} def demojify(text): - text = to_unicode(text) + text = to_str(text) text = remove_unicode_variations(text) return demojize(text, delimiters=("", "")) @@ -27,15 +24,15 @@ def sanitize(text, safe_chars="-_.", demoji=True): Examples: - >>> sanitize("Hello World!") # doctest: +ALLOW_UNICODE + >>> sanitize("Hello World!") 'Hello-World' - >>> sanitize("Hello World!", safe_chars="-_. ") # doctest: +ALLOW_UNICODE + >>> sanitize("Hello World!", safe_chars="-_. ") 'Hello World' - >>> sanitize("\u2764") # doctest: +ALLOW_UNICODE + >>> sanitize("\u2764") 'red_heart' - >>> sanitize("\u2764\ufe00") # doctest: +ALLOW_UNICODE + >>> sanitize("\u2764\ufe00") 'red_heart' - >>> sanitize("\u2764", demoji=False) # doctest: +ALLOW_UNICODE + >>> sanitize("\u2764", demoji=False) '' Args: @@ -51,7 +48,7 @@ def sanitize(text, safe_chars="-_.", demoji=True): slugify.safe_chars = safe_chars _SLUGIFIES[safe_chars] = slugify - text = to_unicode(text) + text = to_str(text) if demoji: text = demojify(text) return slugify(text) diff --git a/src/octoprint/util/version.py b/src/octoprint/util/version.py index 3224242aa..25dc933d1 100644 --- a/src/octoprint/util/version.py +++ b/src/octoprint/util/version.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ This module provides a bunch of utility methods and helpers for version handling. """ @@ -10,7 +7,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp import logging import pkg_resources -from past.builtins import basestring from octoprint import __version__ @@ -65,7 +61,7 @@ def is_octoprint_compatible(*compatibility_entries, **kwargs): octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===") ): - octo_compat = ">={}".format(octo_compat) + octo_compat = f">={octo_compat}" s = pkg_resources.Requirement.parse("OctoPrint" + octo_compat) if octoprint_version in s: @@ -169,7 +165,7 @@ def is_stable(version): False """ - if isinstance(version, basestring): + if isinstance(version, str): version = get_comparable_version(version) if not is_release(version): @@ -198,7 +194,7 @@ def is_release(version): False """ - if isinstance(version, basestring): + if isinstance(version, str): version = get_comparable_version(version) if isinstance(version, tuple): @@ -211,7 +207,7 @@ def is_release(version): def is_prerelease(version): - if isinstance(version, basestring): + if isinstance(version, str): version = get_comparable_version(version) if isinstance(version, tuple): diff --git a/src/octoprint/util/yaml.py b/src/octoprint/util/yaml.py index da1cca6b1..f2ecf628c 100644 --- a/src/octoprint/util/yaml.py +++ b/src/octoprint/util/yaml.py @@ -1,21 +1,16 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import - -import io +from typing import Any, Dict, Hashable, TextIO, Union -def load_from_file(file=None, path=None): +def load_from_file( + file: TextIO = None, path: str = None +) -> Union[Dict[Hashable, Any], list, 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 io.open(path, mode="rt", encoding="utf-8-sig") as f: + with open(path, mode="rt", encoding="utf-8-sig") as f: return load_from_file(file=f) if file is not None: @@ -36,7 +31,7 @@ def load_from_file(file=None, path=None): 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: + with open(path, "wt", encoding="utf-8") as f: return _save_to_file_base(data, file=f, pretty=pretty, **kwargs) if file is not None: diff --git a/src/octoprint/vendor/imp.py b/src/octoprint/vendor/imp.py index 66c417980..db7db08f6 100644 --- a/src/octoprint/vendor/imp.py +++ b/src/octoprint/vendor/imp.py @@ -241,7 +241,7 @@ def load_module(name, file, filename, details): elif type_ == PY_FROZEN: return init_frozen(name) else: - msg = "Don't know how to import {} (type code {})".format(name, type_) + msg = "Don't know how to import {} (type code {})".format(name, type_) raise ImportError(msg, name=name) diff --git a/src/octoprint/vendor/sockjs/tornado/basehandler.py b/src/octoprint/vendor/sockjs/tornado/basehandler.py index 792a7f59e..6efc4201f 100644 --- a/src/octoprint/vendor/sockjs/tornado/basehandler.py +++ b/src/octoprint/vendor/sockjs/tornado/basehandler.py @@ -15,19 +15,13 @@ import logging from tornado.web import RequestHandler from tornado.gen import coroutine -try: - # python 3 - # noinspection PyCompatibility - from urllib.parse import urlparse -except ImportError: - # python 2 - # noinspection PyCompatibility - from urlparse import urlparse +from urllib.parse import urlparse CACHE_TIME = 31536000 LOG = logging.getLogger("tornado.general") + class BaseHandler(RequestHandler): """Base request handler with set of helpers.""" def initialize(self, server): diff --git a/src/octoprint/vendor/sockjs/tornado/websocket.py b/src/octoprint/vendor/sockjs/tornado/websocket.py index a32fb9d1e..45f3affab 100644 --- a/src/octoprint/vendor/sockjs/tornado/websocket.py +++ b/src/octoprint/vendor/sockjs/tornado/websocket.py @@ -4,10 +4,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera import tornado from tornado import escape, gen, websocket -try: - from urllib.parse import urlparse # py3 -except ImportError: - from urlparse import urlparse # py2 +from urllib.parse import urlparse class SockJSWebSocketHandler(websocket.WebSocketHandler): diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py deleted file mode 100644 index 3f710983f..000000000 --- a/src/octoprint/vendor/zeroconf.py +++ /dev/null @@ -1,2265 +0,0 @@ -from __future__ import absolute_import, division, print_function, unicode_literals - -""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine - Copyright 2003 Paul Scott-Murphy, 2014 William McBrine - - This module provides a framework for the use of DNS Service Discovery - using IP multicast. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 - USA -""" - -import enum -import errno -import logging -import re -import select -import socket -import struct -import sys -import threading -import time -import itertools - -import netifaces -from six import binary_type, indexbytes, int2byte, iteritems, text_type -from six.moves import xrange - -__author__ = "Paul Scott-Murphy, William McBrine" -__maintainer__ = "Jakub Stasiak " -__version__ = "0.19.1" -__license__ = "LGPL" - - -__all__ = [ - "__version__", - "Zeroconf", - "ServiceInfo", - "ServiceBrowser", - "Error", - "InterfaceChoice", - "ServiceStateChange", -] - - -log = logging.getLogger(__name__) -log.addHandler(logging.NullHandler()) - -if log.level == logging.NOTSET: - log.setLevel(logging.WARN) - -# Some timing constants - -_UNREGISTER_TIME = 125 -_CHECK_TIME = 175 -_REGISTER_TIME = 225 -_LISTENER_TIME = 200 -_BROWSER_TIME = 500 - -# Some DNS constants - -_MDNS_ADDR = "224.0.0.251" -_MDNS_PORT = 5353 -_DNS_PORT = 53 -_DNS_HOST_TTL = 120 # two minute for host records (A, SRV etc) as-per RFC6762 -_DNS_OTHER_TTL = 4500 # 75 minutes for non-host records (PTR, TXT etc) as-per RFC6762 - -_MAX_MSG_TYPICAL = 1460 # unused -_MAX_MSG_ABSOLUTE = 8966 - -_FLAGS_QR_MASK = 0x8000 # query response mask -_FLAGS_QR_QUERY = 0x0000 # query -_FLAGS_QR_RESPONSE = 0x8000 # response - -_FLAGS_AA = 0x0400 # Authoritative answer -_FLAGS_TC = 0x0200 # Truncated -_FLAGS_RD = 0x0100 # Recursion desired -_FLAGS_RA = 0x8000 # Recursion available - -_FLAGS_Z = 0x0040 # Zero -_FLAGS_AD = 0x0020 # Authentic data -_FLAGS_CD = 0x0010 # Checking disabled - -_CLASS_IN = 1 -_CLASS_CS = 2 -_CLASS_CH = 3 -_CLASS_HS = 4 -_CLASS_NONE = 254 -_CLASS_ANY = 255 -_CLASS_MASK = 0x7FFF -_CLASS_UNIQUE = 0x8000 - -_TYPE_A = 1 -_TYPE_NS = 2 -_TYPE_MD = 3 -_TYPE_MF = 4 -_TYPE_CNAME = 5 -_TYPE_SOA = 6 -_TYPE_MB = 7 -_TYPE_MG = 8 -_TYPE_MR = 9 -_TYPE_NULL = 10 -_TYPE_WKS = 11 -_TYPE_PTR = 12 -_TYPE_HINFO = 13 -_TYPE_MINFO = 14 -_TYPE_MX = 15 -_TYPE_TXT = 16 -_TYPE_AAAA = 28 -_TYPE_SRV = 33 -_TYPE_ANY = 255 - -# Mapping constants to names - -_CLASSES = { - _CLASS_IN: "in", - _CLASS_CS: "cs", - _CLASS_CH: "ch", - _CLASS_HS: "hs", - _CLASS_NONE: "none", - _CLASS_ANY: "any", -} - -_TYPES = { - _TYPE_A: "a", - _TYPE_NS: "ns", - _TYPE_MD: "md", - _TYPE_MF: "mf", - _TYPE_CNAME: "cname", - _TYPE_SOA: "soa", - _TYPE_MB: "mb", - _TYPE_MG: "mg", - _TYPE_MR: "mr", - _TYPE_NULL: "null", - _TYPE_WKS: "wks", - _TYPE_PTR: "ptr", - _TYPE_HINFO: "hinfo", - _TYPE_MINFO: "minfo", - _TYPE_MX: "mx", - _TYPE_TXT: "txt", - _TYPE_AAAA: "quada", - _TYPE_SRV: "srv", - _TYPE_ANY: "any", -} - -_HAS_A_TO_Z = re.compile(r"[A-Za-z]") -_HAS_ONLY_A_TO_Z_NUM_HYPHEN = re.compile(r"^[A-Za-z0-9\-]+$") -_HAS_ASCII_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") - - -@enum.unique -class InterfaceChoice(enum.Enum): - Default = 1 - All = 2 - - -@enum.unique -class ServiceStateChange(enum.Enum): - Added = 1 - Removed = 2 - - -HOST_ONLY_NETWORK_MASK = "255.255.255.255" - - -# utility functions - - -def current_time_millis(): - """Current system time in milliseconds""" - return time.time() * 1000 - - -def service_type_name(type_): - """ - Validate a fully qualified service name, instance or subtype. [rfc6763] - - Returns fully qualified service name. - - Domain names used by mDNS-SD take the following forms: - - . <_tcp|_udp> . local. - . . <_tcp|_udp> . local. - ._sub . . <_tcp|_udp> . local. - - 1) must end with 'local.' - - This is true because we are implementing mDNS and since the 'm' means - multi-cast, the 'local.' domain is mandatory. - - 2) local is preceded with either '_udp.' or '_tcp.' - - 3) service name precedes <_tcp|_udp> - - The rules for Service Names [RFC6335] state that they may be no more - than fifteen characters long (not counting the mandatory underscore), - consisting of only letters, digits, and hyphens, must begin and end - with a letter or digit, must not contain consecutive hyphens, and - must contain at least one letter. - - The instance name and sub type may be up to 63 bytes. - - The portion of the Service Instance Name is a user- - friendly name consisting of arbitrary Net-Unicode text [RFC5198]. It - MUST NOT contain ASCII control characters (byte values 0x00-0x1F and - 0x7F) [RFC20] but otherwise is allowed to contain any characters, - without restriction, including spaces, uppercase, lowercase, - punctuation -- including dots -- accented characters, non-Roman text, - and anything else that may be represented using Net-Unicode. - - :param type_: Type, SubType or service name to validate - :return: fully qualified service name (eg: _http._tcp.local.) - """ - if not (type_.endswith("._tcp.local.") or type_.endswith("._udp.local.")): - raise BadTypeInNameException( - "Type '%s' must end with '._tcp.local.' or '._udp.local.'" % type_ - ) - - remaining = type_[: -len("._tcp.local.")].split(".") - name = remaining.pop() - if not name: - raise BadTypeInNameException("No Service name found") - - if len(remaining) == 1 and len(remaining[0]) == 0: - raise BadTypeInNameException("Type '%s' must not start with '.'" % type_) - - if name[0] != "_": - raise BadTypeInNameException("Service name (%s) must start with '_'" % name) - - # remove leading underscore - name = name[1:] - - if len(name) > 15: - raise BadTypeInNameException("Service name (%s) must be <= 15 bytes" % name) - - if "--" in name: - raise BadTypeInNameException("Service name (%s) must not contain '--'" % name) - - if "-" in (name[0], name[-1]): - raise BadTypeInNameException( - "Service name (%s) may not start or end with '-'" % name - ) - - if not _HAS_A_TO_Z.search(name): - raise BadTypeInNameException( - "Service name (%s) must contain at least one letter (eg: 'A-Z')" % name - ) - - if not _HAS_ONLY_A_TO_Z_NUM_HYPHEN.search(name): - raise BadTypeInNameException( - "Service name (%s) must contain only these characters: " - "A-Z, a-z, 0-9, hyphen ('-')" % name - ) - - if remaining and remaining[-1] == "_sub": - remaining.pop() - if len(remaining) == 0 or len(remaining[0]) == 0: - raise BadTypeInNameException("_sub requires a subtype name") - - if len(remaining) > 1: - remaining = [".".join(remaining)] - - if remaining: - length = len(remaining[0].encode("utf-8")) - if length > 63: - raise BadTypeInNameException("Too long: '%s'" % remaining[0]) - - if _HAS_ASCII_CONTROL_CHARS.search(remaining[0]): - raise BadTypeInNameException( - "Ascii control character 0x00-0x1F and 0x7F illegal in '%s'" - % remaining[0] - ) - - return "_" + name + type_[-len("._tcp.local.") :] - - -# Exceptions - - -class Error(Exception): - pass - - -class IncomingDecodeError(Error): - pass - - -class NonUniqueNameException(Error): - pass - - -class NamePartTooLongException(Error): - pass - - -class AbstractMethodException(Error): - pass - - -class BadTypeInNameException(Error): - pass - - -# implementation classes - - -class QuietLogger(object): - _seen_logs = {} - - @classmethod - def log_exception_warning(cls, logger_data=None): - exc_info = sys.exc_info() - exc_str = str(exc_info[1]) - if exc_str not in cls._seen_logs: - # log at warning level the first time this is seen - cls._seen_logs[exc_str] = exc_info - logger = log.warning - else: - logger = log.debug - if logger_data is not None: - logger(*logger_data) - logger("Exception occurred:", exc_info=exc_info) - - @classmethod - def log_warning_once(cls, *args): - msg_str = args[0] - if msg_str not in cls._seen_logs: - cls._seen_logs[msg_str] = 0 - logger = log.warning - else: - logger = log.debug - cls._seen_logs[msg_str] += 1 - logger(*args) - - -class DNSEntry(object): - - """A DNS entry""" - - def __init__(self, name, type_, class_): - self.key = name.lower() - self.name = name - self.type = type_ - self.class_ = class_ & _CLASS_MASK - self.unique = (class_ & _CLASS_UNIQUE) != 0 - - def __eq__(self, other): - """Equality test on name, type, and class""" - return ( - self.name == other.name - and self.type == other.type - and self.class_ == other.class_ - and isinstance(other, DNSEntry) - ) - - def __ne__(self, other): - """Non-equality test""" - return not self.__eq__(other) - - @staticmethod - def get_class_(class_): - """Class accessor""" - return _CLASSES.get(class_, "?(%s)" % class_) - - @staticmethod - def get_type(t): - """Type accessor""" - return _TYPES.get(t, "?(%s)" % t) - - def to_string(self, hdr, other): - """String representation with additional information""" - result = "%s[%s,%s" % ( - hdr, - self.get_type(self.type), - self.get_class_(self.class_), - ) - if self.unique: - result += "-unique," - else: - result += "," - result += self.name - if other is not None: - result += ",%s]" % other - else: - result += "]" - return result - - -class DNSQuestion(DNSEntry): - - """A DNS question entry""" - - def __init__(self, name, type_, class_): - DNSEntry.__init__(self, name, type_, class_) - - def answered_by(self, rec): - """Returns true if the question is answered by the record""" - return ( - self.class_ == rec.class_ - and (self.type == rec.type or self.type == _TYPE_ANY) - and self.name == rec.name - ) - - def __repr__(self): - """String representation""" - return DNSEntry.to_string(self, "question", None) - - -class DNSRecord(DNSEntry): - - """A DNS record - like a DNS entry, but has a TTL""" - - def __init__(self, name, type_, class_, ttl): - DNSEntry.__init__(self, name, type_, class_) - self.ttl = ttl - self.created = current_time_millis() - self._expiration_time = self.get_expiration_time(100) - self._stale_time = self.get_expiration_time(50) - - def __eq__(self, other): - """Abstract method""" - raise AbstractMethodException - - def suppressed_by(self, msg): - """Returns true if any answer in a message can suffice for the - information held in this record.""" - for record in msg.answers: - if self.suppressed_by_answer(record): - return True - return False - - def suppressed_by_answer(self, other): - """Returns true if another record has same name, type and class, - and if its TTL is at least half of this record's.""" - return self == other and other.ttl > (self.ttl / 2) - - def get_expiration_time(self, percent): - """Returns the time at which this record will have expired - by a certain percentage.""" - return self.created + (percent * self.ttl * 10) - - def get_remaining_ttl(self, now): - """Returns the remaining TTL in seconds.""" - return max(0, (self._expiration_time - now) / 1000) - - def is_expired(self, now): - """Returns true if this record has expired.""" - return self._expiration_time <= now - - def is_stale(self, now): - """Returns true if this record is at least half way expired.""" - return self._stale_time <= now - - def reset_ttl(self, other): - """Sets this record's TTL and created time to that of - another record.""" - self.created = other.created - self.ttl = other.ttl - - def write(self, out): - """Abstract method""" - raise AbstractMethodException - - def to_string(self, other): - """String representation with additional information""" - arg = "%s/%s,%s" % ( - self.ttl, - self.get_remaining_ttl(current_time_millis()), - other, - ) - return DNSEntry.to_string(self, "record", arg) - - -class DNSAddress(DNSRecord): - - """A DNS address record""" - - def __init__(self, name, type_, class_, ttl, address): - DNSRecord.__init__(self, name, type_, class_, ttl) - self.address = address - - def write(self, out): - """Used in constructing an outgoing packet""" - out.write_string(self.address) - - def __eq__(self, other): - """Tests equality on address""" - return ( - isinstance(other, DNSAddress) - and self.address == other.address - and DNSEntry.__eq__(self, other) - ) - - def __repr__(self): - """String representation""" - try: - return str(socket.inet_ntoa(self.address)) - except Exception: # TODO stop catching all Exceptions - return str(self.address) - - -class DNSHinfo(DNSRecord): - - """A DNS host information record""" - - def __init__(self, name, type_, class_, ttl, cpu, os): - DNSRecord.__init__(self, name, type_, class_, ttl) - try: - self.cpu = cpu.decode("utf-8") - except AttributeError: - self.cpu = cpu - try: - self.os = os.decode("utf-8") - except AttributeError: - self.os = os - - def write(self, out): - """Used in constructing an outgoing packet""" - out.write_character_string(self.cpu.encode("utf-8")) - out.write_character_string(self.os.encode("utf-8")) - - def __eq__(self, other): - """Tests equality on cpu and os""" - return ( - isinstance(other, DNSHinfo) - and self.cpu == other.cpu - and self.os == other.os - and DNSEntry.__eq__(self, other) - ) - - def __repr__(self): - """String representation""" - return self.cpu + " " + self.os - - -class DNSPointer(DNSRecord): - - """A DNS pointer record""" - - def __init__(self, name, type_, class_, ttl, alias): - DNSRecord.__init__(self, name, type_, class_, ttl) - self.alias = alias - - def write(self, out): - """Used in constructing an outgoing packet""" - out.write_name(self.alias) - - def __eq__(self, other): - """Tests equality on alias""" - return ( - isinstance(other, DNSPointer) - and self.alias == other.alias - and DNSEntry.__eq__(self, other) - ) - - def __repr__(self): - """String representation""" - return self.to_string(self.alias) - - -class DNSText(DNSRecord): - - """A DNS text record""" - - def __init__(self, name, type_, class_, ttl, text): - assert isinstance(text, (bytes, type(None))) - DNSRecord.__init__(self, name, type_, class_, ttl) - self.text = text - - def write(self, out): - """Used in constructing an outgoing packet""" - out.write_string(self.text) - - def __eq__(self, other): - """Tests equality on text""" - return ( - isinstance(other, DNSText) - and self.text == other.text - and DNSEntry.__eq__(self, other) - ) - - def __repr__(self): - """String representation""" - if len(self.text) > 10: - return self.to_string(self.text[:7]) + "..." - else: - return self.to_string(self.text) - - -class DNSService(DNSRecord): - - """A DNS service record""" - - def __init__(self, name, type_, class_, ttl, priority, weight, port, server): - DNSRecord.__init__(self, name, type_, class_, ttl) - self.priority = priority - self.weight = weight - self.port = port - self.server = server - - def write(self, out): - """Used in constructing an outgoing packet""" - out.write_short(self.priority) - out.write_short(self.weight) - out.write_short(self.port) - out.write_name(self.server) - - def __eq__(self, other): - """Tests equality on priority, weight, port and server""" - return ( - isinstance(other, DNSService) - and self.priority == other.priority - and self.weight == other.weight - and self.port == other.port - and self.server == other.server - and DNSEntry.__eq__(self, other) - ) - - def __repr__(self): - """String representation""" - return self.to_string("%s:%s" % (self.server, self.port)) - - -class DNSIncoming(QuietLogger): - - """Object representation of an incoming DNS packet""" - - def __init__(self, data): - """Constructor from string holding bytes of packet""" - self.offset = 0 - self.data = data - self.questions = [] - self.answers = [] - self.id = 0 - self.flags = 0 - self.num_questions = 0 - self.num_answers = 0 - self.num_authorities = 0 - self.num_additionals = 0 - self.valid = False - - try: - self.read_header() - self.read_questions() - self.read_others() - self.valid = True - - except (IndexError, struct.error, IncomingDecodeError): - self.log_exception_warning( - ("Choked at offset %d while unpacking %r", self.offset, data) - ) - - def unpack(self, format_): - length = struct.calcsize(format_) - info = struct.unpack(format_, self.data[self.offset : self.offset + length]) - self.offset += length - return info - - def read_header(self): - """Reads header portion of packet""" - ( - self.id, - self.flags, - self.num_questions, - self.num_answers, - self.num_authorities, - self.num_additionals, - ) = self.unpack(b"!6H") - - def read_questions(self): - """Reads questions section of packet""" - for i in xrange(self.num_questions): - name = self.read_name() - type_, class_ = self.unpack(b"!HH") - - question = DNSQuestion(name, type_, class_) - self.questions.append(question) - - # def read_int(self): - # """Reads an integer from the packet""" - # return self.unpack(b'!I')[0] - - def read_character_string(self): - """Reads a character string from the packet""" - length = indexbytes(self.data, self.offset) - self.offset += 1 - return self.read_string(length) - - def read_string(self, length): - """Reads a string of a given length from the packet""" - info = self.data[self.offset : self.offset + length] - self.offset += length - return info - - def read_unsigned_short(self): - """Reads an unsigned short from the packet""" - return self.unpack(b"!H")[0] - - def read_others(self): - """Reads the answers, authorities and additionals section of the - packet""" - n = self.num_answers + self.num_authorities + self.num_additionals - for i in xrange(n): - domain = self.read_name() - type_, class_, ttl, length = self.unpack(b"!HHiH") - - rec = None - if type_ == _TYPE_A: - rec = DNSAddress(domain, type_, class_, ttl, self.read_string(4)) - elif type_ == _TYPE_CNAME or type_ == _TYPE_PTR: - rec = DNSPointer(domain, type_, class_, ttl, self.read_name()) - elif type_ == _TYPE_TXT: - rec = DNSText(domain, type_, class_, ttl, self.read_string(length)) - elif type_ == _TYPE_SRV: - rec = DNSService( - domain, - type_, - class_, - ttl, - self.read_unsigned_short(), - self.read_unsigned_short(), - self.read_unsigned_short(), - self.read_name(), - ) - elif type_ == _TYPE_HINFO: - rec = DNSHinfo( - domain, - type_, - class_, - ttl, - self.read_character_string(), - self.read_character_string(), - ) - elif type_ == _TYPE_AAAA: - rec = DNSAddress(domain, type_, class_, ttl, self.read_string(16)) - else: - # Try to ignore types we don't know about - # Skip the payload for the resource record so the next - # records can be parsed correctly - self.offset += length - - if rec is not None: - self.answers.append(rec) - - def is_query(self): - """Returns true if this is a query""" - return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY - - def is_response(self): - """Returns true if this is a response""" - return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE - - def read_utf(self, offset, length): - """Reads a UTF-8 string of a given length from the packet""" - return text_type(self.data[offset : offset + length], "utf-8", "replace") - - def read_name(self): - """Reads a domain name from the packet""" - result = "" - off = self.offset - next_ = -1 - first = off - - while True: - length = indexbytes(self.data, off) - off += 1 - if length == 0: - break - t = length & 0xC0 - if t == 0x00: - result = "".join((result, self.read_utf(off, length) + ".")) - off += length - elif t == 0xC0: - if next_ < 0: - next_ = off + 1 - off = ((length & 0x3F) << 8) | indexbytes(self.data, off) - if off >= first: - raise IncomingDecodeError("Bad domain name (circular) at %s" % (off,)) - first = off - else: - raise IncomingDecodeError("Bad domain name at %s" % (off,)) - - if next_ >= 0: - self.offset = next_ - else: - self.offset = off - - return result - - -class DNSOutgoing(object): - - """Object representation of an outgoing packet""" - - def __init__(self, flags, multicast=True): - self.finished = False - self.id = 0 - self.multicast = multicast - self.flags = flags - self.names = {} - self.data = [] - self.size = 12 - self.state = self.State.init - - self.questions = [] - self.answers = [] - self.authorities = [] - self.additionals = [] - - def __repr__(self): - return "" % ", ".join( - [ - "multicast=%s" % self.multicast, - "flags=%s" % self.flags, - "questions=%s" % self.questions, - "answers=%s" % self.answers, - "authorities=%s" % self.authorities, - "additionals=%s" % self.additionals, - ] - ) - - class State(enum.Enum): - init = 0 - finished = 1 - - def add_question(self, record): - """Adds a question""" - self.questions.append(record) - - def add_answer(self, inp, record): - """Adds an answer""" - if not record.suppressed_by(inp): - self.add_answer_at_time(record, 0) - - def add_answer_at_time(self, record, now): - """Adds an answer if it does not expire by a certain time""" - if record is not None: - if now == 0 or not record.is_expired(now): - self.answers.append((record, now)) - - def add_authorative_answer(self, record): - """Adds an authoritative answer""" - self.authorities.append(record) - - def add_additional_answer(self, record): - """Adds an additional answer - - From: RFC 6763, DNS-Based Service Discovery, February 2013 - - 12. DNS Additional Record Generation - - DNS has an efficiency feature whereby a DNS server may place - additional records in the additional section of the DNS message. - These additional records are records that the client did not - explicitly request, but the server has reasonable grounds to expect - that the client might request them shortly, so including them can - save the client from having to issue additional queries. - - This section recommends which additional records SHOULD be generated - to improve network efficiency, for both Unicast and Multicast DNS-SD - responses. - - 12.1. PTR Records - - When including a DNS-SD Service Instance Enumeration or Selective - Instance Enumeration (subtype) PTR record in a response packet, the - server/responder SHOULD include the following additional records: - - o The SRV record(s) named in the PTR rdata. - o The TXT record(s) named in the PTR rdata. - o All address records (type "A" and "AAAA") named in the SRV rdata. - - 12.2. SRV Records - - When including an SRV record in a response packet, the - server/responder SHOULD include the following additional records: - - o All address records (type "A" and "AAAA") named in the SRV rdata. - - """ - self.additionals.append(record) - - def pack(self, format_, value): - self.data.append(struct.pack(format_, value)) - self.size += struct.calcsize(format_) - - def write_byte(self, value): - """Writes a single byte to the packet""" - self.pack(b"!c", int2byte(value)) - - def insert_short(self, index, value): - """Inserts an unsigned short in a certain position in the packet""" - self.data.insert(index, struct.pack(b"!H", value)) - self.size += 2 - - def write_short(self, value): - """Writes an unsigned short to the packet""" - self.pack(b"!H", value) - - def write_int(self, value): - """Writes an unsigned integer to the packet""" - self.pack(b"!I", int(value)) - - def write_string(self, value): - """Writes a string to the packet""" - assert isinstance(value, bytes) - self.data.append(value) - self.size += len(value) - - def write_utf(self, s): - """Writes a UTF-8 string of a given length to the packet""" - utfstr = s.encode("utf-8") - length = len(utfstr) - if length > 64: - raise NamePartTooLongException - self.write_byte(length) - self.write_string(utfstr) - - def write_character_string(self, value): - assert isinstance(value, bytes) - length = len(value) - if length > 256: - raise NamePartTooLongException - self.write_byte(length) - self.write_string(value) - - def write_name(self, name): - """ - Write names to packet - - 18.14. Name Compression - - When generating Multicast DNS messages, implementations SHOULD use - name compression wherever possible to compress the names of resource - records, by replacing some or all of the resource record name with a - compact two-byte reference to an appearance of that data somewhere - earlier in the message [RFC1035]. - """ - - # split name into each label - parts = name.split(".") - if not parts[-1]: - parts.pop() - - # construct each suffix - name_suffices = [".".join(parts[i:]) for i in range(len(parts))] - - # look for an existing name or suffix - for count, sub_name in enumerate(name_suffices): - if sub_name in self.names: - break - else: - count += 1 - - # note the new names we are saving into the packet - for suffix in name_suffices[:count]: - self.names[suffix] = self.size + len(name) - len(suffix) - 1 - - # write the new names out. - for part in parts[:count]: - self.write_utf(part) - - # if we wrote part of the name, create a pointer to the rest - if count != len(name_suffices): - # Found substring in packet, create pointer - index = self.names[name_suffices[count]] - self.write_byte((index >> 8) | 0xC0) - self.write_byte(index & 0xFF) - else: - # this is the end of a name - self.write_byte(0) - - def write_question(self, question): - """Writes a question to the packet""" - self.write_name(question.name) - self.write_short(question.type) - self.write_short(question.class_) - - def write_record(self, record, now): - """Writes a record (answer, authoritative answer, additional) to - the packet""" - if self.state == self.State.finished: - return 1 - - start_data_length, start_size = len(self.data), self.size - self.write_name(record.name) - self.write_short(record.type) - if record.unique and self.multicast: - self.write_short(record.class_ | _CLASS_UNIQUE) - else: - self.write_short(record.class_) - if now == 0: - self.write_int(record.ttl) - else: - self.write_int(record.get_remaining_ttl(now)) - index = len(self.data) - - # Adjust size for the short we will write before this record - self.size += 2 - record.write(self) - self.size -= 2 - - length = sum((len(d) for d in self.data[index:])) - # Here is the short we adjusted for - self.insert_short(index, length) - - # if we go over, then rollback and quit - if self.size > _MAX_MSG_ABSOLUTE: - while len(self.data) > start_data_length: - self.data.pop() - self.size = start_size - self.state = self.State.finished - return 1 - return 0 - - def packet(self): - """Returns a string containing the packet's bytes - - No further parts should be added to the packet once this - is done.""" - - overrun_answers, overrun_authorities, overrun_additionals = 0, 0, 0 - - if self.state != self.State.finished: - for question in self.questions: - self.write_question(question) - for answer, time_ in self.answers: - overrun_answers += self.write_record(answer, time_) - for authority in self.authorities: - overrun_authorities += self.write_record(authority, 0) - for additional in self.additionals: - overrun_additionals += self.write_record(additional, 0) - self.state = self.State.finished - - self.insert_short(0, len(self.additionals) - overrun_additionals) - self.insert_short(0, len(self.authorities) - overrun_authorities) - self.insert_short(0, len(self.answers) - overrun_answers) - self.insert_short(0, len(self.questions)) - self.insert_short(0, self.flags) - if self.multicast: - self.insert_short(0, 0) - else: - self.insert_short(0, self.id) - return b"".join(self.data) - - -class DNSCache(object): - - """A cache of DNS entries""" - - def __init__(self): - self.cache = {} - - def add(self, entry): - """Adds an entry""" - self.cache.setdefault(entry.key, []).append(entry) - - def remove(self, entry): - """Removes an entry""" - try: - list_ = self.cache[entry.key] - list_.remove(entry) - except (KeyError, ValueError): - pass - - def get(self, entry): - """Gets an entry by key. Will return None if there is no - matching entry.""" - try: - list_ = self.cache[entry.key] - for cached_entry in list_: - if entry.__eq__(cached_entry): - return cached_entry - except (KeyError, ValueError): - return None - - def get_by_details(self, name, type_, class_): - """Gets an entry by details. Will return None if there is - no matching entry.""" - entry = DNSEntry(name, type_, class_) - return self.get(entry) - - def entries_with_name(self, name): - """Returns a list of entries whose key matches the name.""" - try: - return self.cache[name.lower()] - except KeyError: - return [] - - def current_entry_with_name_and_alias(self, name, alias): - now = current_time_millis() - for record in self.entries_with_name(name): - if ( - record.type == _TYPE_PTR - and not record.is_expired(now) - and record.alias == alias - ): - return record - - def entries(self): - """Returns a list of all entries""" - if not self.cache: - return [] - else: - # avoid size change during iteration by copying the cache - values = list(self.cache.values()) - return list(itertools.chain.from_iterable(values)) - - -class Engine(threading.Thread): - - """An engine wraps read access to sockets, allowing objects that - need to receive data from sockets to be called back when the - sockets are ready. - - A reader needs a handle_read() method, which is called when the socket - it is interested in is ready for reading. - - Writers are not implemented here, because we only send short - packets. - """ - - def __init__(self, zc): - threading.Thread.__init__(self, name="zeroconf-Engine") - self.daemon = True - self.zc = zc - self.readers = {} # maps socket to reader - self.timeout = 5 - self.condition = threading.Condition() - self.start() - - def run(self): - while not self.zc.done: - with self.condition: - rs = self.readers.keys() - if len(rs) == 0: - # No sockets to manage, but we wait for the timeout - # or addition of a socket - self.condition.wait(self.timeout) - - if len(rs) != 0: - try: - rr, wr, er = select.select(rs, [], [], self.timeout) - if not self.zc.done: - for socket_ in rr: - reader = self.readers.get(socket_) - if reader: - reader.handle_read(socket_) - - except (select.error, socket.error) as e: - # If the socket was closed by another thread, during - # shutdown, ignore it and exit - if e.args[0] != socket.EBADF or not self.zc.done: - raise - - def add_reader(self, reader, socket_): - with self.condition: - self.readers[socket_] = reader - self.condition.notify() - - def del_reader(self, socket_): - with self.condition: - del self.readers[socket_] - self.condition.notify() - - -class Listener(QuietLogger): - - """A Listener is used by this module to listen on the multicast - group to which DNS messages are sent, allowing the implementation - to cache information as it arrives. - - It requires registration with an Engine object in order to have - the read() method called when a socket is available for reading.""" - - def __init__(self, zc): - self.zc = zc - self.data = None - - def handle_read(self, socket_): - try: - data, (addr, port) = socket_.recvfrom(_MAX_MSG_ABSOLUTE) - except Exception: - self.log_exception_warning() - return - - log.debug("Received from %r:%r: %r ", addr, port, data) - - self.data = data - msg = DNSIncoming(data) - if not msg.valid: - pass - - elif msg.is_query(): - # Always multicast responses - if port == _MDNS_PORT: - self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT) - - # If it's not a multicast query, reply via unicast - # and multicast - elif port == _DNS_PORT: - self.zc.handle_query(msg, addr, port) - self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT) - - else: - self.zc.handle_response(msg) - - -class Reaper(threading.Thread): - - """A Reaper is used by this module to remove cache entries that - have expired.""" - - def __init__(self, zc): - threading.Thread.__init__(self, name="zeroconf-Reaper") - self.daemon = True - self.zc = zc - self.start() - - def run(self): - while True: - self.zc.wait(10 * 1000) - if self.zc.done: - return - now = current_time_millis() - for record in self.zc.cache.entries(): - if record.is_expired(now): - self.zc.update_record(now, record) - self.zc.cache.remove(record) - - -class Signal(object): - def __init__(self): - self._handlers = [] - - def fire(self, **kwargs): - for h in list(self._handlers): - h(**kwargs) - - @property - def registration_interface(self): - return SignalRegistrationInterface(self._handlers) - - -class SignalRegistrationInterface(object): - def __init__(self, handlers): - self._handlers = handlers - - def register_handler(self, handler): - self._handlers.append(handler) - return self - - def unregister_handler(self, handler): - self._handlers.remove(handler) - return self - - -class ServiceBrowser(threading.Thread): - - """Used to browse for a service of a specific type. - - The listener object will have its add_service() and - remove_service() methods called when this browser - discovers changes in the services availability.""" - - def __init__(self, zc, type_, handlers=None, listener=None): - """Creates a browser for a specific type""" - assert handlers or listener, "You need to specify at least one handler" - if not type_.endswith(service_type_name(type_)): - raise BadTypeInNameException - threading.Thread.__init__(self, name="zeroconf-ServiceBrowser_" + type_) - self.daemon = True - self.zc = zc - self.type = type_ - self.services = {} - self.next_time = current_time_millis() - self.delay = _BROWSER_TIME - self._handlers_to_call = [] - - self._service_state_changed = Signal() - - self.done = False - - if hasattr(handlers, "add_service"): - listener = handlers - handlers = None - - handlers = handlers or [] - - if listener: - - def on_change(zeroconf, service_type, name, state_change): - args = (zeroconf, service_type, name) - if state_change is ServiceStateChange.Added: - listener.add_service(*args) - elif state_change is ServiceStateChange.Removed: - listener.remove_service(*args) - else: - raise NotImplementedError(state_change) - - handlers.append(on_change) - - for h in handlers: - self.service_state_changed.register_handler(h) - - self.start() - - @property - def service_state_changed(self): - return self._service_state_changed.registration_interface - - def update_record(self, zc, now, record): - """Callback invoked by Zeroconf when new information arrives. - - Updates information required by browser in the Zeroconf cache.""" - - def enqueue_callback(state_change, name): - self._handlers_to_call.append( - lambda zeroconf: self._service_state_changed.fire( - zeroconf=zeroconf, - service_type=self.type, - name=name, - state_change=state_change, - ) - ) - - if record.type == _TYPE_PTR and record.name == self.type: - expired = record.is_expired(now) - service_key = record.alias.lower() - try: - old_record = self.services[service_key] - except KeyError: - if not expired: - self.services[service_key] = record - enqueue_callback(ServiceStateChange.Added, record.alias) - else: - if not expired: - old_record.reset_ttl(record) - else: - del self.services[service_key] - enqueue_callback(ServiceStateChange.Removed, record.alias) - return - - expires = record.get_expiration_time(75) - if expires < self.next_time: - self.next_time = expires - - def cancel(self): - self.done = True - self.zc.remove_listener(self) - self.join() - - def run(self): - self.zc.add_listener(self, DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) - - while True: - now = current_time_millis() - if len(self._handlers_to_call) == 0 and self.next_time > now: - self.zc.wait(self.next_time - now) - if self.zc.done or self.done: - return - now = current_time_millis() - if self.next_time <= now: - out = DNSOutgoing(_FLAGS_QR_QUERY) - out.add_question(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) - for record in self.services.values(): - if not record.is_expired(now): - out.add_answer_at_time(record, now) - - self.zc.send(out) - self.next_time = now + self.delay - self.delay = min(20 * 1000, self.delay * 2) - - if len(self._handlers_to_call) > 0 and not self.zc.done: - handler = self._handlers_to_call.pop(0) - handler(self.zc) - - -class ServiceInfo(object): - - """Service information""" - - def __init__( - self, - type_, - name, - addresses=None, - port=None, - weight=0, - priority=0, - properties=None, - server=None, - host_ttl=_DNS_HOST_TTL, - other_ttl=_DNS_OTHER_TTL, - ): - """Create a service description. - - type_: fully qualified service type name - name: fully qualified service name - addresses: List of IP addresses as unsigned short (IPv4), - network byte order - port: port that the service runs on - weight: weight of the service - priority: priority of the service - properties: dictionary of properties (or a string holding the - bytes for the text field) - server: fully qualified name for service host (defaults to name) - host_ttl: ttl used for A/SRV records - other_ttl: ttl used for PTR/TXT records - """ - - if not type_.endswith(service_type_name(name)): - raise BadTypeInNameException - self.type = type_ - self.name = name - if addresses is not None: - self._addresses = addresses - else: - self._addresses = [] - # This results in an ugly error when registering, better check now - invalid = [a for a in self._addresses if not isinstance(a, bytes) or len(a) != 4] - if invalid: - raise TypeError( - "Addresses must be bytes, got %s. Hint: convert string addresses " - "with socket.inet_pton" % invalid - ) - self.port = port - self.weight = weight - self.priority = priority - if server: - self.server = server - else: - self.server = name - self._properties = {} - self._set_properties(properties) - self.host_ttl = host_ttl - self.other_ttl = other_ttl - - @property - def addresses(self): - """IPv4 addresses of this service.""" - return self._addresses - - @addresses.setter - def addresses(self, value): - """Replace the addresses list. - - This replaces all currently stored addresses. - """ - self._addresses = value - - @property - def properties(self): - return self._properties - - def _set_properties(self, properties): - """Sets properties and text of this info from a dictionary""" - if isinstance(properties, dict): - self._properties = properties - list_ = [] - result = b"" - for key, value in iteritems(properties): - if isinstance(key, text_type): - key = key.encode("utf-8") - - if value is None: - suffix = b"" - elif isinstance(value, text_type): - suffix = value.encode("utf-8") - elif isinstance(value, binary_type): - suffix = value - elif isinstance(value, int): - if value: - suffix = b"true" - else: - suffix = b"false" - else: - suffix = b"" - list_.append(b"=".join((key, suffix))) - for item in list_: - result = b"".join((result, int2byte(len(item)), item)) - self.text = result - else: - self.text = properties - - def _set_text(self, text): - """Sets properties and text given a text field""" - self.text = text - result = {} - end = len(text) - index = 0 - strs = [] - while index < end: - length = indexbytes(text, index) - index += 1 - strs.append(text[index : index + length]) - index += length - - for s in strs: - parts = s.split(b"=", 1) - try: - key, value = parts - except ValueError: - # No equals sign at all - key = s - value = False - else: - if value == b"true": - value = True - elif value == b"false" or not value: - value = False - - # Only update non-existent properties - if key and result.get(key) is None: - result[key] = value - - self._properties = result - - def get_name(self): - """Name accessor""" - if self.type is not None and self.name.endswith("." + self.type): - return self.name[: len(self.name) - len(self.type) - 1] - return self.name - - def update_record(self, zc, now, record): - """Updates service information from a DNS record""" - if record is not None and not record.is_expired(now): - if record.type == _TYPE_A: - # if record.name == self.name: - if record.name == self.server: - if record.address not in self._addresses: - self._addresses.append(record.address) - elif record.type == _TYPE_SRV: - if record.name == self.name: - self.server = record.server - self.port = record.port - self.weight = record.weight - self.priority = record.priority - # self.address = None - self.update_record( - zc, now, zc.cache.get_by_details(self.server, _TYPE_A, _CLASS_IN) - ) - elif record.type == _TYPE_TXT: - if record.name == self.name: - self._set_text(record.text) - - def request(self, zc, timeout): - """Returns true if the service could be discovered on the - network, and updates this object with details discovered. - """ - now = current_time_millis() - delay = _LISTENER_TIME - next_ = now + delay - last = now + timeout - - record_types_for_check_cache = [ - (_TYPE_SRV, _CLASS_IN), - (_TYPE_TXT, _CLASS_IN), - ] - if self.server is not None: - record_types_for_check_cache.append((_TYPE_A, _CLASS_IN)) - for record_type in record_types_for_check_cache: - cached = zc.cache.get_by_details(self.name, *record_type) - if cached: - self.update_record(zc, now, cached) - - if self.server is not None and self.text is not None and self._addresses: - return True - - try: - zc.add_listener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN)) - while self.server is None or self.text is None or not self._addresses: - if last <= now: - return False - if next_ <= now: - out = DNSOutgoing(_FLAGS_QR_QUERY) - out.add_question(DNSQuestion(self.name, _TYPE_SRV, _CLASS_IN)) - out.add_answer_at_time( - zc.cache.get_by_details(self.name, _TYPE_SRV, _CLASS_IN), now - ) - - out.add_question(DNSQuestion(self.name, _TYPE_TXT, _CLASS_IN)) - out.add_answer_at_time( - zc.cache.get_by_details(self.name, _TYPE_TXT, _CLASS_IN), now - ) - - if self.server is not None: - out.add_question(DNSQuestion(self.server, _TYPE_A, _CLASS_IN)) - out.add_answer_at_time( - zc.cache.get_by_details(self.server, _TYPE_A, _CLASS_IN), now - ) - zc.send(out) - next_ = now + delay - delay *= 2 - - zc.wait(min(next_, last) - now) - now = current_time_millis() - finally: - zc.remove_listener(self) - - return True - - def __eq__(self, other): - """Tests equality of service name""" - return isinstance(other, ServiceInfo) and other.name == self.name - - def __ne__(self, other): - """Non-equality test""" - return not self.__eq__(other) - - def __repr__(self): - """String representation""" - return "%s(%s)" % ( - type(self).__name__, - ", ".join( - "%s=%r" % (name, getattr(self, name)) - for name in ( - "type", - "name", - "addresses", - "port", - "weight", - "priority", - "server", - "properties", - ) - ), - ) - - -class ZeroconfServiceTypes(object): - """ - Return all of the advertised services on any local networks - """ - - def __init__(self): - self.found_services = set() - - def add_service(self, zc, type_, name): - self.found_services.add(name) - - def remove_service(self, zc, type_, name): - pass - - @classmethod - def find(cls, zc=None, timeout=5, interfaces=InterfaceChoice.All): - """ - Return all of the advertised services on any local networks. - - :param zc: Zeroconf() instance. Pass in if already have an - instance running or if non-default interfaces are needed - :param timeout: seconds to wait for any responses - :return: tuple of service type strings - """ - local_zc = zc or Zeroconf(interfaces=interfaces) - listener = cls() - browser = ServiceBrowser( - local_zc, "_services._dns-sd._udp.local.", listener=listener - ) - - # wait for responses - time.sleep(timeout) - - # close down anything we opened - if zc is None: - local_zc.close() - else: - browser.cancel() - - return tuple(sorted(listener.found_services)) - - -def get_all_addresses(address_family): - return list( - { - addr["addr"] - for iface in netifaces.interfaces() - for addr in netifaces.ifaddresses(iface).get(address_family, []) - if addr.get("netmask") != HOST_ONLY_NETWORK_MASK - } - ) - - -def normalize_interface_choice(choice, address_family): - if choice is InterfaceChoice.Default: - choice = ["0.0.0.0"] - elif choice is InterfaceChoice.All: - choice = get_all_addresses(address_family) - return choice - - -def new_socket(): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - - # SO_REUSEADDR should be equivalent to SO_REUSEPORT for - # multicast UDP sockets (p 731, "TCP/IP Illustrated, - # Volume 2"), but some BSD-derived systems require - # SO_REUSEPORT to be specified explicity. Also, not all - # versions of Python have SO_REUSEPORT available. - # Catch OSError and socket.error for kernel versions <3.9 because lacking - # SO_REUSEPORT support. - try: - reuseport = socket.SO_REUSEPORT - except AttributeError: - pass - else: - try: - s.setsockopt(socket.SOL_SOCKET, reuseport, 1) - except (OSError, socket.error) as err: - # OSError on python 3, socket.error on python 2 - if not err.errno == errno.ENOPROTOOPT: - raise - - # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and - # IP_MULTICAST_LOOP socket options as an unsigned char. - ttl = struct.pack(b"B", 255) - s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) - loop = struct.pack(b"B", 1) - s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop) - - s.bind(("", _MDNS_PORT)) - return s - - -def get_errno(e): - assert isinstance(e, socket.error) - return e.args[0] - - -class Zeroconf(QuietLogger): - - """Implementation of Zeroconf Multicast DNS Service Discovery - - Supports registration, unregistration, queries and browsing. - """ - - def __init__( - self, - interfaces=InterfaceChoice.All, - ): - """Creates an instance of the Zeroconf class, establishing - multicast communications, listening and reaping threads. - - :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses - """ - # hook for threads - self._GLOBAL_DONE = False - - self._listen_socket = new_socket() - interfaces = normalize_interface_choice(interfaces, socket.AF_INET) - - self._respond_sockets = [] - - for i in interfaces: - log.debug("Adding %r to multicast group", i) - try: - self._listen_socket.setsockopt( - socket.IPPROTO_IP, - socket.IP_ADD_MEMBERSHIP, - socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i), - ) - except socket.error as e: - if get_errno(e) == errno.EADDRINUSE: - log.info( - "Address in use when adding %s to multicast group, " - "it is expected to happen on some systems", - i, - ) - elif get_errno(e) == errno.EADDRNOTAVAIL: - log.info( - "Address not available when adding %s to multicast " - "group, it is expected to happen on some systems", - i, - ) - continue - else: - raise - - respond_socket = new_socket() - respond_socket.setsockopt( - socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i) - ) - - self._respond_sockets.append(respond_socket) - - self.listeners = [] - self.browsers = {} - self.services = {} - self.servicetypes = {} - - self.cache = DNSCache() - - self.condition = threading.Condition() - - self.engine = Engine(self) - self.listener = Listener(self) - self.engine.add_reader(self.listener, self._listen_socket) - self.reaper = Reaper(self) - - self.debug = None - - @property - def done(self): - return self._GLOBAL_DONE - - def wait(self, timeout): - """Calling thread waits for a given number of milliseconds or - until notified.""" - with self.condition: - self.condition.wait(timeout / 1000) - - def notify_all(self): - """Notifies all waiting threads""" - with self.condition: - self.condition.notify_all() - - def get_service_info(self, type_, name, timeout=3000): - """Returns network's service information for a particular - name and type, or None if no service matches by the timeout, - which defaults to 3 seconds.""" - info = ServiceInfo(type_, name) - if info.request(self, timeout): - return info - - def add_service_listener(self, type_, listener): - """Adds a listener for a particular service type. This object - will then have its update_record method called when information - arrives for that type.""" - self.remove_service_listener(listener) - self.browsers[listener] = ServiceBrowser(self, type_, listener) - - def remove_service_listener(self, listener): - """Removes a listener from the set that is currently listening.""" - if listener in self.browsers: - self.browsers[listener].cancel() - del self.browsers[listener] - - def remove_all_service_listeners(self): - """Removes a listener from the set that is currently listening.""" - for listener in [k for k in self.browsers]: - self.remove_service_listener(listener) - - def register_service(self, info, ttl=_DNS_HOST_TTL, allow_name_change=False): - """Registers service information to the network with a default TTL - of 120 seconds. Zeroconf will then respond to requests for - information for that service. The name of the service may be - changed if needed to make it unique on the network.""" - self.check_service(info, allow_name_change) - self.services[info.name.lower()] = info - if info.type in self.servicetypes: - self.servicetypes[info.type] += 1 - else: - self.servicetypes[info.type] = 1 - now = current_time_millis() - next_time = now - i = 0 - while i < 3: - if now < next_time: - self.wait(next_time - now) - now = current_time_millis() - continue - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer_at_time( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0 - ) - out.add_answer_at_time( - DNSService( - info.name, - _TYPE_SRV, - _CLASS_IN, - ttl, - info.priority, - info.weight, - info.port, - info.server, - ), - 0, - ) - - out.add_answer_at_time( - DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0 - ) - for address in info.addresses: - out.add_answer_at_time( - DNSAddress(info.server, _TYPE_A, _CLASS_IN, ttl, address), 0 - ) - self.send(out) - i += 1 - next_time += _REGISTER_TIME - - def unregister_service(self, info): - """Unregister a service.""" - try: - del self.services[info.name.lower()] - if self.servicetypes[info.type] > 1: - self.servicetypes[info.type] -= 1 - else: - del self.servicetypes[info.type] - except Exception as e: # TODO stop catching all Exceptions - log.exception("Unknown error, possibly benign: %r", e) - now = current_time_millis() - next_time = now - i = 0 - while i < 3: - if now < next_time: - self.wait(next_time - now) - now = current_time_millis() - continue - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer_at_time( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0 - ) - out.add_answer_at_time( - DNSService( - info.name, - _TYPE_SRV, - _CLASS_IN, - 0, - info.priority, - info.weight, - info.port, - info.name, - ), - 0, - ) - out.add_answer_at_time( - DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0 - ) - - for address in info.addresses: - out.add_answer_at_time( - DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, address), 0 - ) - self.send(out) - i += 1 - next_time += _UNREGISTER_TIME - - def unregister_all_services(self): - """Unregister all registered services.""" - if len(self.services) > 0: - now = current_time_millis() - next_time = now - i = 0 - while i < 3: - if now < next_time: - self.wait(next_time - now) - now = current_time_millis() - continue - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - for info in self.services.values(): - out.add_answer_at_time( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0 - ) - out.add_answer_at_time( - DNSService( - info.name, - _TYPE_SRV, - _CLASS_IN, - 0, - info.priority, - info.weight, - info.port, - info.server, - ), - 0, - ) - out.add_answer_at_time( - DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0 - ) - for address in info.addresses: - out.add_answer_at_time( - DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, address), 0 - ) - self.send(out) - i += 1 - next_time += _UNREGISTER_TIME - - def check_service(self, info, allow_name_change): - """Checks the network for a unique service name, modifying the - ServiceInfo passed in if it is not unique.""" - - # This is kind of funky because of the subtype based tests - # need to make subtypes a first class citizen - service_name = service_type_name(info.name) - if not info.type.endswith(service_name): - raise BadTypeInNameException - - instance_name = info.name[: -len(service_name) - 1] - next_instance_number = 2 - - now = current_time_millis() - next_time = now - i = 0 - while i < 3: - # check for a name conflict - while self.cache.current_entry_with_name_and_alias(info.type, info.name): - if not allow_name_change: - raise NonUniqueNameException - - # change the name and look for a conflict - info.name = "%s-%s.%s" % (instance_name, next_instance_number, info.type) - next_instance_number += 1 - service_type_name(info.name) - next_time = now - i = 0 - - if now < next_time: - self.wait(next_time - now) - now = current_time_millis() - continue - - out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA) - self.debug = out - out.add_question(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN)) - out.add_authorative_answer( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, info.other_ttl, info.name) - ) - self.send(out) - i += 1 - next_time += _CHECK_TIME - - def add_listener(self, listener, question): - """Adds a listener for a given question. The listener will have - its update_record method called when information is available to - answer the question.""" - now = current_time_millis() - self.listeners.append(listener) - if question is not None: - for record in self.cache.entries_with_name(question.name): - if question.answered_by(record) and not record.is_expired(now): - listener.update_record(self, now, record) - self.notify_all() - - def remove_listener(self, listener): - """Removes a listener.""" - try: - self.listeners.remove(listener) - self.notify_all() - except Exception as e: # TODO stop catching all Exceptions - log.exception("Unknown error, possibly benign: %r", e) - - def update_record(self, now, rec): - """Used to notify listeners of new information that has updated - a record.""" - for listener in self.listeners: - listener.update_record(self, now, rec) - self.notify_all() - - def handle_response(self, msg): - """Deal with incoming response packets. All answers - are held in the cache, and listeners are notified.""" - now = current_time_millis() - for record in msg.answers: - if record in self.cache.entries(): - if record.is_expired(now): - self.cache.remove(record) - else: - entry = self.cache.get(record) - if entry is not None: - entry.reset_ttl(record) - else: - self.cache.add(record) - - for record in msg.answers: - self.update_record(now, record) - - def handle_query(self, msg, addr, port): - """Deal with incoming query packets. Provides a response if - possible.""" - out = None - - # Support unicast client responses - # - if port != _MDNS_PORT: - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=False) - for question in msg.questions: - out.add_question(question) - - for question in msg.questions: - if question.type == _TYPE_PTR: - if question.name == "_services._dns-sd._udp.local.": - for stype in self.servicetypes.keys(): - if out is None: - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer( - msg, - DNSPointer( - "_services._dns-sd._udp.local.", - _TYPE_PTR, - _CLASS_IN, - _DNS_OTHER_TTL, - stype, - ), - ) - for service in self.services.values(): - if question.name == service.type: - if out is None: - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer( - msg, - DNSPointer( - service.type, - _TYPE_PTR, - _CLASS_IN, - service.other_ttl, - service.name, - ), - ) - - # Add recommended additional answers according to - # https://tools.ietf.org/html/rfc6763#section-12.1. - out.add_additional_answer( - DNSService( - service.name, - _TYPE_SRV, - _CLASS_IN | _CLASS_UNIQUE, - service.host_ttl, - service.priority, - service.weight, - service.port, - service.server, - ) - ) - out.add_additional_answer( - DNSText( - service.name, - _TYPE_TXT, - _CLASS_IN | _CLASS_UNIQUE, - service.other_ttl, - service.text, - ) - ) - for address in service.addresses: - out.add_additional_answer( - DNSAddress( - service.server, - _TYPE_A, - _CLASS_IN | _CLASS_UNIQUE, - service.host_ttl, - address, - ) - ) - else: - try: - if out is None: - out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - - # Answer A record queries for any service addresses we know - if question.type in (_TYPE_A, _TYPE_ANY): - for service in self.services.values(): - if service.server == question.name.lower(): - for address in service.addresses: - out.add_answer( - msg, - DNSAddress( - question.name, - _TYPE_A, - _CLASS_IN | _CLASS_UNIQUE, - service.host_ttl, - address, - ), - ) - - service = self.services.get(question.name.lower(), None) - if not service: - continue - - if question.type in (_TYPE_SRV, _TYPE_ANY): - out.add_answer( - msg, - DNSService( - question.name, - _TYPE_SRV, - _CLASS_IN | _CLASS_UNIQUE, - service.host_ttl, - service.priority, - service.weight, - service.port, - service.server, - ), - ) - if question.type in (_TYPE_TXT, _TYPE_ANY): - out.add_answer( - msg, - DNSText( - question.name, - _TYPE_TXT, - _CLASS_IN | _CLASS_UNIQUE, - service.other_ttl, - service.text, - ), - ) - if question.type == _TYPE_SRV: - for address in service.addresses: - out.add_additional_answer( - DNSAddress( - service.server, - _TYPE_A, - _CLASS_IN | _CLASS_UNIQUE, - service.host_ttl, - address, - ) - ) - except Exception: # TODO stop catching all Exceptions - self.log_exception_warning() - - if out is not None and out.answers: - out.id = msg.id - self.send(out, addr, port) - - def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): - """Sends an outgoing packet.""" - packet = out.packet() - if len(packet) > _MAX_MSG_ABSOLUTE: - self.log_warning_once( - "Dropping %r over-sized packet (%d bytes) %r", out, len(packet), packet - ) - return - log.debug("Sending %r (%d bytes) as %r...", out, len(packet), packet) - for s in self._respond_sockets: - if self._GLOBAL_DONE: - return - try: - bytes_sent = s.sendto(packet, 0, (addr, port)) - except Exception: # TODO stop catching all Exceptions - # on send errors, log the exception and keep going - self.log_exception_warning() - else: - if bytes_sent != len(packet): - self.log_warning_once( - "!!! sent %d out of %d bytes to %r" % (bytes_sent, len(packet)), s - ) - - def close(self): - """Ends the background threads, and prevent this instance from - servicing further queries.""" - if not self._GLOBAL_DONE: - self._GLOBAL_DONE = True - # remove service listeners - self.remove_all_service_listeners() - self.unregister_all_services() - - # shutdown recv socket and thread - self.engine.del_reader(self._listen_socket) - self._listen_socket.close() - self.engine.join() - - # shutdown the rest - self.notify_all() - self.reaper.join() - for s in self._respond_sockets: - s.close() diff --git a/src/octoprint_client/__init__.py b/src/octoprint_client/__init__.py index 5622adc5e..6ce5df44f 100644 --- a/src/octoprint_client/__init__.py +++ b/src/octoprint_client/__init__.py @@ -1,10 +1,6 @@ -# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import json import time @@ -16,19 +12,19 @@ def build_base_url( https=False, httpuser=None, httppass=None, host=None, port=None, prefix=None ): protocol = "https" if https else "http" - httpauth = "{}:{}@".format(httpuser, httppass) if httpuser and httppass else "" + httpauth = f"{httpuser}:{httppass}@" if httpuser and httppass else "" host = host if host else "127.0.0.1" - port = ":{}".format(port) if port else ":5000" + port = f":{port}" if port else ":5000" prefix = prefix if prefix else "" - return "{}://{}{}{}{}".format(protocol, httpauth, host, port, prefix) + return f"{protocol}://{httpauth}{host}{port}{prefix}" 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 @@ -222,7 +218,7 @@ class SocketClient(object): return False -class Client(object): +class Client: def __init__(self, baseurl, apikey): self.baseurl = baseurl self.apikey = apikey @@ -290,14 +286,12 @@ class Client(object): import os if not os.path.isfile(file_path): - raise ValueError( - "{} cannot be uploaded since it is not a file".format(file_path) - ) + raise ValueError(f"{file_path} cannot be uploaded since it is not a file") if file_name is None: file_name = os.path.basename(file_path) - with io.open(file_path, "rb") as fp: + with open(file_path, "rb") as fp: if content_type: files = {"file": (file_name, fp, content_type)} else: @@ -414,7 +408,7 @@ class Client(object): class CustomSocketClient(SocketClient): def auth(self, username, key): - self.send({"auth": "{}:{}".format(username, key)}) + self.send({"auth": f"{username}:{key}"}) def throttle(self, factor): self.send({"throttle": factor}) diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py index 3154c8350..38d359e05 100644 --- a/src/octoprint_setuptools/__init__.py +++ b/src/octoprint_setuptools/__init__.py @@ -1,7 +1,13 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function -# NO unicode_literals because Py2 setuptool can't cope with them +### NOTE ################################################################################# +# This file has to stay format compatible to Python 2, or pip under Python 2 will +# not be able to detect that OctoPrint requires Python 3 but instead fail with a +# syntax error. +# +# So, no f-strings, no walrus operators, no pyupgrade or codemods. +########################################################################################## __author__ = u"Gina Häußge " __license__ = u"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -65,12 +71,6 @@ def has_requirement(requirement, requirements): if requirement is None or requirements is None: return False - # from past.builtins import basestring - - # assert isinstance(requirement, basestring) - # assert isinstance(requirements, (list, tuple)) - # assert all(list(map(lambda x: x is not None and isinstance(x, basestring), requirements))) - requirement = requirement.lower() requirements = [r.lower() for r in requirements] compat = [ diff --git a/tests/_fixups.py b/tests/_fixups.py index 687373080..9efed1cd3 100644 --- a/tests/_fixups.py +++ b/tests/_fixups.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import sys # noqa: F401 -OPEN_SIGNATURE = "io.open" +OPEN_SIGNATURE = "builtins.open" diff --git a/tests/access/__init__.py b/tests/access/__init__.py index 9f2422c25..0d0c509ce 100644 --- a/tests/access/__init__.py +++ b/tests/access/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access """ diff --git a/tests/access/_plugins/permissions_plugin.py b/tests/access/_plugins/permissions_plugin.py index 4dcfa47ed..413aa640e 100644 --- a/tests/access/_plugins/permissions_plugin.py +++ b/tests/access/_plugins/permissions_plugin.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - - def plugin_permissions(components): return [ { diff --git a/tests/access/groups/__init__.py b/tests/access/groups/__init__.py index 44a448ac1..199a89cd2 100644 --- a/tests/access/groups/__init__.py +++ b/tests/access/groups/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.groups """ diff --git a/tests/access/groups/test_groupmanager.py b/tests/access/groups/test_groupmanager.py index 796c52a82..7391d3082 100644 --- a/tests/access/groups/test_groupmanager.py +++ b/tests/access/groups/test_groupmanager.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.groups.GroupManager """ diff --git a/tests/access/test_permissions.py b/tests/access/test_permissions.py index a9e48f976..2b58b3827 100644 --- a/tests/access/test_permissions.py +++ b/tests/access/test_permissions.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.permissions """ diff --git a/tests/access/users/__init__.py b/tests/access/users/__init__.py index 776c9719d..480de5365 100644 --- a/tests/access/users/__init__.py +++ b/tests/access/users/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.users """ diff --git a/tests/access/users/test_usermanager.py b/tests/access/users/test_usermanager.py index cb77132d8..f1faa1f7d 100644 --- a/tests/access/users/test_usermanager.py +++ b/tests/access/users/test_usermanager.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.users.UserManager """ diff --git a/tests/access/users/test_users.py b/tests/access/users/test_users.py index ebf3a91dc..149c099ec 100644 --- a/tests/access/users/test_users.py +++ b/tests/access/users/test_users.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for octoprint.access.users """ diff --git a/tests/filemanager/__init__.py b/tests/filemanager/__init__.py index 020b1101c..d5cdb3d70 100644 --- a/tests/filemanager/__init__.py +++ b/tests/filemanager/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.filemanager.``. """ diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 52b45c910..b876c5a23 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -8,9 +5,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import io import unittest +from unittest import mock import _fixups -import mock import octoprint.filemanager import octoprint.filemanager.util @@ -685,7 +682,7 @@ class FileManagerTest(unittest.TestCase): # assert that shutil was asked to copy the concatenated multistream self.assertEqual(2, len(mocked_shutil.call_args_list)) - self.assertTrue(isinstance(mocked_shutil.call_args_list[0].args[0], io.BytesIO)) + self.assertTrue(isinstance(mocked_shutil.call_args_list[0][0][0], io.BytesIO)) # assert that the temporary file was deleted mocked_os.assert_called_once_with("tmp.file") diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py index 73fa296de..53023ec71 100644 --- a/tests/filemanager/test_localstorage.py +++ b/tests/filemanager/test_localstorage.py @@ -1,16 +1,12 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 os import os.path import unittest +from unittest import mock -import mock import pytest from ddt import data, ddt, unpack @@ -31,7 +27,7 @@ pathvalidate_available_only = pytest.mark.skipif( ) -class FileWrapper(object): +class FileWrapper: def __init__(self, filename): self.path = os.path.join( os.path.dirname(os.path.realpath(__file__)), "_files", filename @@ -41,7 +37,7 @@ class FileWrapper(object): blocksize = 65536 hash = hashlib.sha1() - with io.open(self.path, "rb") as f: + with open(self.path, "rb") as f: buffer = f.read(blocksize) while len(buffer) > 0: hash.update(buffer) @@ -853,7 +849,7 @@ class LocalStorageTest(unittest.TestCase): # prepare import yaml - with io.open(yaml_path, "wt") as f: + with open(yaml_path, "wt") as f: yaml.safe_dump(metadata, f) # migrate @@ -865,7 +861,7 @@ class LocalStorageTest(unittest.TestCase): import json - with io.open(json_path, "rt", encoding="utf-8") as f: + with open(json_path, encoding="utf-8") as f: json_metadata = json.load(f) self.assertDictEqual(metadata, json_metadata) diff --git a/tests/manual_tests/always_update.py b/tests/manual_tests/always_update.py index e832647b4..539d15089 100644 --- a/tests/manual_tests/always_update.py +++ b/tests/manual_tests/always_update.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Place in ~/.octoprint/plugins & restart server to test: @@ -20,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}, diff --git a/tests/plugin/__init__.py b/tests/plugin/__init__.py index 8cbb6ecdd..14e2a7d67 100644 --- a/tests/plugin/__init__.py +++ b/tests/plugin/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.plugin``. """ diff --git a/tests/plugin/_plugins/another_ordered_hook_plugin.py b/tests/plugin/_plugins/another_ordered_hook_plugin.py index 7253de000..e0acedf61 100644 --- a/tests/plugin/_plugins/another_ordered_hook_plugin.py +++ b/tests/plugin/_plugins/another_ordered_hook_plugin.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - - def callback(*args, **kwargs): pass diff --git a/tests/plugin/_plugins/asset_plugin.py b/tests/plugin/_plugins/asset_plugin.py index 5936acc4e..69dd52eb4 100644 --- a/tests/plugin/_plugins/asset_plugin.py +++ b/tests/plugin/_plugins/asset_plugin.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import octoprint.plugin diff --git a/tests/plugin/_plugins/hook_plugin.py b/tests/plugin/_plugins/hook_plugin.py index 518c5d1d7..a0d315a8c 100644 --- a/tests/plugin/_plugins/hook_plugin.py +++ b/tests/plugin/_plugins/hook_plugin.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - - def hook_startup(): return "success" diff --git a/tests/plugin/_plugins/mixed_plugin/__init__.py b/tests/plugin/_plugins/mixed_plugin/__init__.py index d721a97bc..273657fed 100644 --- a/tests/plugin/_plugins/mixed_plugin/__init__.py +++ b/tests/plugin/_plugins/mixed_plugin/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/tests/plugin/_plugins/not_a_plugin.py b/tests/plugin/_plugins/not_a_plugin.py index c58e04714..3ec98f389 100644 --- a/tests/plugin/_plugins/not_a_plugin.py +++ b/tests/plugin/_plugins/not_a_plugin.py @@ -1,2 +1 @@ -# -*- coding: utf-8 -*- print("I'm not a plugin") diff --git a/tests/plugin/_plugins/one_ordered_hook_plugin.py b/tests/plugin/_plugins/one_ordered_hook_plugin.py index 109b699d1..fc9171fd5 100644 --- a/tests/plugin/_plugins/one_ordered_hook_plugin.py +++ b/tests/plugin/_plugins/one_ordered_hook_plugin.py @@ -1,7 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - - def callback(*args, **kwargs): pass diff --git a/tests/plugin/_plugins/settings_plugin.py b/tests/plugin/_plugins/settings_plugin.py index 7399b1fb2..45b63565b 100644 --- a/tests/plugin/_plugins/settings_plugin.py +++ b/tests/plugin/_plugins/settings_plugin.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import octoprint.plugin diff --git a/tests/plugin/_plugins/startup_plugin.py b/tests/plugin/_plugins/startup_plugin.py index 1a1e25bab..56e29dd95 100644 --- a/tests/plugin/_plugins/startup_plugin.py +++ b/tests/plugin/_plugins/startup_plugin.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import octoprint.plugin diff --git a/tests/plugin/test_core.py b/tests/plugin/test_core.py index e15fd3364..afaa3d265 100644 --- a/tests/plugin/test_core.py +++ b/tests/plugin/test_core.py @@ -1,19 +1,15 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest +from unittest import mock import ddt -import mock import octoprint.plugin import octoprint.plugin.core -from octoprint.util import to_native_str ##~~ Helpers for testing mixin type extraction -class A(object): +class A: pass @@ -33,7 +29,7 @@ class A1_1(A_1): pass -class B(object): +class B: pass @@ -41,7 +37,7 @@ class B_1(B): pass -class C(object): +class C: pass @@ -49,7 +45,7 @@ class C_1(C): pass -class D(object): +class D: pass @@ -442,7 +438,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 ) diff --git a/tests/plugin/test_settings.py b/tests/plugin/test_settings.py index b845d1cbe..c8d956ff0 100644 --- a/tests/plugin/test_settings.py +++ b/tests/plugin/test_settings.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" @@ -8,13 +5,12 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import unittest import warnings +from unittest import mock -import mock from ddt import data, ddt, unpack import octoprint.plugin import octoprint.settings -from octoprint.util import to_native_str @ddt @@ -148,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) @@ -165,8 +161,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) @data( @@ -388,8 +383,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) @@ -406,8 +401,7 @@ class SettingsTestCase(unittest.TestCase): self.assertEqual(1, len(w)) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue( - "{old} has been renamed to {new}".format(old=deprecated, new=current) - in str(w[-1].message) + f"{deprecated} has been renamed to {current}" in str(w[-1].message) ) def test_global_get_basefolder(self): @@ -423,7 +417,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}.log", path.replace(os.sep, "/"), ) @@ -436,7 +430,7 @@ class SettingsTestCase(unittest.TestCase): self.settings.getBaseFolder.assert_called_once_with("logs") self.assertEqual( - "/some/folder/plugin_{key}_mypostfix.log".format(key=self.plugin_key), + f"/some/folder/plugin_{self.plugin_key}_mypostfix.log", path.replace(os.sep, "/"), ) diff --git a/tests/plugin/test_types_blueprint.py b/tests/plugin/test_types_blueprint.py index 7cf18d6a1..7a6cf3cac 100644 --- a/tests/plugin/test_types_blueprint.py +++ b/tests/plugin/test_types_blueprint.py @@ -1,9 +1,5 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest - -import mock +from unittest import mock import octoprint.plugin @@ -138,9 +134,7 @@ class BlueprintPluginTest(unittest.TestCase): self.assertEqual(result, blueprint) - MockBlueprint.assert_called_once_with( - "plugin.myplugin", "myplugin", **expected_kwargs - ) + MockBlueprint.assert_called_once_with("myplugin", "myplugin", **expected_kwargs) blueprint.add_url_rule.assert_called_once_with( "/some/path", "route_method", view_func=plugin.route_method, methods=["GET"] ) diff --git a/tests/plugin/test_types_settings.py b/tests/plugin/test_types_settings.py index 55f217c8b..cb8bf0874 100644 --- a/tests/plugin/test_types_settings.py +++ b/tests/plugin/test_types_settings.py @@ -1,9 +1,5 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest - -import mock +from unittest import mock import octoprint.plugin diff --git a/tests/plugins/__init__.py b/tests/plugins/__init__.py index dc614c5ab..14f7b298f 100644 --- a/tests/plugins/__init__.py +++ b/tests/plugins/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for bundled plugins. """ diff --git a/tests/plugins/pluginmanager/__init__.py b/tests/plugins/pluginmanager/__init__.py index 092cd3e34..e69de29bb 100644 --- a/tests/plugins/pluginmanager/__init__.py +++ b/tests/plugins/pluginmanager/__init__.py @@ -1,2 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals diff --git a/tests/plugins/pluginmanager/test_notification_filter.py b/tests/plugins/pluginmanager/test_notification_filter.py index 1b8a1e1c0..60844df6a 100644 --- a/tests/plugins/pluginmanager/test_notification_filter.py +++ b/tests/plugins/pluginmanager/test_notification_filter.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest import ddt diff --git a/tests/printer/__init__.py b/tests/printer/__init__.py index dbef1b48a..076d1af18 100644 --- a/tests/printer/__init__.py +++ b/tests/printer/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.printer``. """ diff --git a/tests/printer/test_estimation.py b/tests/printer/test_estimation.py index 3101015ce..e0dc14e81 100644 --- a/tests/printer/test_estimation.py +++ b/tests/printer/test_estimation.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - from octoprint.printer.estimation import TimeEstimationHelper __author__ = "Gina Häußge " diff --git a/tests/printer/test_script.py b/tests/printer/test_script.py index b580e4ef7..57a0fefb4 100644 --- a/tests/printer/test_script.py +++ b/tests/printer/test_script.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" import unittest - -from mock import ANY, MagicMock, call, patch +from unittest.mock import ANY, MagicMock, call, patch from octoprint.printer.standard import Printer diff --git a/tests/server/__init__.py b/tests/server/__init__.py index c6a35a27e..b91d60b16 100644 --- a/tests/server/__init__.py +++ b/tests/server/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.server``. """ diff --git a/tests/server/api/__init__.py b/tests/server/api/__init__.py index c1260aadb..671d96ee1 100644 --- a/tests/server/api/__init__.py +++ b/tests/server/api/__init__.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- """ Unit tests for ``octoprint.server.api``. """ -from __future__ import absolute_import, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" diff --git a/tests/server/api/test_system.py b/tests/server/api/test_system.py index 0438ec0a3..f3fe6add5 100644 --- a/tests/server/api/test_system.py +++ b/tests/server/api/test_system.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- """ Unit tests for ``octoprint.server.api`` system. """ -from __future__ import absolute_import, unicode_literals __author__ = "Gina Häußge " __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -11,8 +9,7 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import unittest - -import mock +from unittest import mock class GetFolderUsageTest(unittest.TestCase): diff --git a/tests/server/util/__init__.py b/tests/server/util/__init__.py index ef390f2ec..396dc6759 100644 --- a/tests/server/util/__init__.py +++ b/tests/server/util/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.server.util``. """ diff --git a/tests/server/util/test_flask.py b/tests/server/util/test_flask.py index 397eeccf7..114220c26 100644 --- a/tests/server/util/test_flask.py +++ b/tests/server/util/test_flask.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.server.util.flask``. """ @@ -11,8 +8,8 @@ __copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms import unittest +from unittest import mock -import mock from ddt import data, ddt, unpack from octoprint.server.util.flask import ( diff --git a/tests/server/util/test_tornado.py b/tests/server/util/test_tornado.py index 30cabf7e4..ccbb9404c 100644 --- a/tests/server/util/test_tornado.py +++ b/tests/server/util/test_tornado.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.server.util.tornado``. """ diff --git a/tests/server/util/test_webassets.py b/tests/server/util/test_webassets.py index ec440ca61..2e51773fa 100644 --- a/tests/server/util/test_webassets.py +++ b/tests/server/util/test_webassets.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.server.util.flask``. """ diff --git a/tests/settings/__init__.py b/tests/settings/__init__.py index b177016d5..146c642e7 100644 --- a/tests/settings/__init__.py +++ b/tests/settings/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.settings``. """ diff --git a/tests/settings/test_settings.py b/tests/settings/test_settings.py index 2535518e4..7bf91cb7a 100644 --- a/tests/settings/test_settings.py +++ b/tests/settings/test_settings.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Tests for OctoPrint's Settings class @@ -13,7 +10,6 @@ Tests for OctoPrint's Settings class import contextlib import hashlib -import io import os import re import shutil @@ -30,11 +26,11 @@ import octoprint.settings @ddt.ddt class TestSettings(unittest.TestCase): def _load_yaml(self, fname): - with io.open(fname, "rt", encoding="utf-8") as f: + with open(fname, encoding="utf-8") as f: return yaml.safe_load(f) def _dump_yaml(self, fname, config): - with io.open(fname, "wt", encoding="utf-8") as f: + with open(fname, "wt", encoding="utf-8") as f: yaml.safe_dump(config, f) def setUp(self): @@ -181,7 +177,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNone after 3.x upgrade. self.assertFalse( match_result, - "string matched and it shouldn't have: {!r}".format(terminal_string), + f"string matched and it shouldn't have: {terminal_string!r}", ) def test_temperature_regex_matches(self): @@ -207,7 +203,7 @@ class TestSettings(unittest.TestCase): # can switch to assertIsNotNone after 3.x upgrade. self.assertTrue( match_result, - "string did not match and it should have: {!r}".format(terminal_string), + f"string did not match and it should have: {terminal_string!r}", ) ##~~ test getters diff --git a/tests/slicing/__init__.py b/tests/slicing/__init__.py index 5c8b8e35b..93ee0c153 100644 --- a/tests/slicing/__init__.py +++ b/tests/slicing/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.slicing``. """ diff --git a/tests/slicing/test_slicingmanager.py b/tests/slicing/test_slicingmanager.py index d27d73f7c..33d1e779c 100644 --- a/tests/slicing/test_slicingmanager.py +++ b/tests/slicing/test_slicingmanager.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 unittest - -import mock +from unittest import mock import octoprint.slicing @@ -120,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 diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 991bdb9de..b621cb344 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest +from unittest import mock import _fixups -import mock import octoprint.daemon @@ -136,7 +133,7 @@ class DaemonTest(unittest.TestCase): self.assertListEqual( mock_open.mock_calls, [ - mock.call(mock_devnull, "rt", encoding="utf-8"), + mock.call(mock_devnull, encoding="utf-8"), mock.call(mock_devnull, "at+", encoding="utf-8"), mock.call(mock_devnull, "at+", encoding="utf-8"), ], @@ -406,14 +403,14 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() # assert self.assertEqual(result, pid) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_get_pid_ioerror(self): # setup @@ -426,7 +423,7 @@ class DaemonTest(unittest.TestCase): # assert self.assertIsNone(result) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_get_pid_valueerror(self): # setup @@ -435,14 +432,14 @@ class DaemonTest(unittest.TestCase): # test with mock.patch( _fixups.OPEN_SIGNATURE, - mock.mock_open(read_data="{}\n".format(pid)), + mock.mock_open(read_data=f"{pid}\n"), create=True, ) as m: result = self.daemon.get_pid() # assert self.assertIsNone(result) - m.assert_called_once_with(self.pidfile, "rt", encoding="utf-8") + m.assert_called_once_with(self.pidfile, encoding="utf-8") def test_set_pid(self): # setup @@ -455,7 +452,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") def test_set_pid_int(self): # setup @@ -468,7 +465,7 @@ class DaemonTest(unittest.TestCase): # assert m.assert_called_once_with(self.pidfile, "wt+", encoding="utf-8") handle = m() - handle.write.assert_called_once_with("{}\n".format(pid)) + handle.write.assert_called_once_with(f"{pid}\n") @mock.patch("os.path.isfile") @mock.patch("os.remove") diff --git a/tests/test_octoprint_setuptools.py b/tests/test_octoprint_setuptools.py index 405b3c205..ae4624591 100644 --- a/tests/test_octoprint_setuptools.py +++ b/tests/test_octoprint_setuptools.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest import ddt diff --git a/tests/test_settings.py b/tests/test_settings.py index 5f961ffe1..050aff109 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/timelapse/__init__.py b/tests/timelapse/__init__.py index 38405297a..d97bd1b1e 100644 --- a/tests/timelapse/__init__.py +++ b/tests/timelapse/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.timelapse``. """ diff --git a/tests/timelapse/test_timelapse_helpers.py b/tests/timelapse/test_timelapse_helpers.py index 05ef704de..1129dbb38 100644 --- a/tests/timelapse/test_timelapse_helpers.py +++ b/tests/timelapse/test_timelapse_helpers.py @@ -1,21 +1,13 @@ -# -*- 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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" -import unittest - -import ddt - -try: - import unittest.mock as mock -except ImportError: - import mock - import os import time +import unittest from collections import OrderedDict, namedtuple +from unittest import mock + +import ddt import octoprint.plugin import octoprint.settings @@ -63,7 +55,7 @@ class TimelapseTest(unittest.TestCase): self.assertEqual(expected, actual) @mock.patch("os.remove") - @mock.patch("octoprint.timelapse.scandir") + @mock.patch("os.scandir") def test_delete_unrendered_timelapse(self, mock_scandir, mock_remove): ## prepare @@ -96,7 +88,7 @@ class TimelapseTest(unittest.TestCase): @mock.patch("time.time") @mock.patch("os.remove") - @mock.patch("octoprint.timelapse.scandir") + @mock.patch("os.scandir") def test_delete_old_unrendered_timelapses(self, mock_scandir, mock_remove, mock_time): ## prepare @@ -135,7 +127,7 @@ class TimelapseTest(unittest.TestCase): expected_deletion_calls = list(map(mock.call, expected_deletions)) self.assertListEqual(mock_remove.mock_calls, expected_deletion_calls) - @mock.patch("octoprint.timelapse.scandir") + @mock.patch("os.scandir") def test_get_finished_timelapses(self, mock_listdir): ## prepare @@ -161,7 +153,7 @@ class TimelapseTest(unittest.TestCase): self.assertEqual(result[1]["name"], "two.mpg") self.assertEqual(result[1]["bytes"], 2048) - @mock.patch("octoprint.timelapse.scandir") + @mock.patch("os.scandir") def test_unrendered_timelapses(self, mock_scandir): ## prepare files = {} diff --git a/tests/timelapse/test_timelapse_renderjob.py b/tests/timelapse/test_timelapse_renderjob.py index 5ebde491c..5ee64543f 100644 --- a/tests/timelapse/test_timelapse_renderjob.py +++ b/tests/timelapse/test_timelapse_renderjob.py @@ -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) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/__init__.py b/tests/util/__init__.py index 8a3d5df04..4bbbcc1cf 100644 --- a/tests/util/__init__.py +++ b/tests/util/__init__.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - """ Unit tests for ``octoprint.util``. """ diff --git a/tests/util/test_caseinsensitive_set.py b/tests/util/test_caseinsensitive_set.py index aa38a5591..ba9178297 100644 --- a/tests/util/test_caseinsensitive_set.py +++ b/tests/util/test_caseinsensitive_set.py @@ -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) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/test_comm.py b/tests/util/test_comm.py index d4fe62d70..6cd3ecf1e 100644 --- a/tests/util/test_comm.py +++ b/tests/util/test_comm.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - import unittest +from unittest import mock import ddt -import mock import octoprint.util.comm diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py index 24f76f3e3..3082339d1 100644 --- a/tests/util/test_comm_helpers.py +++ b/tests/util/test_comm_helpers.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/tests/util/test_counted_event.py b/tests/util/test_counted_event.py index 1cc9d137a..e0e6b2863 100644 --- a/tests/util/test_counted_event.py +++ b/tests/util/test_counted_event.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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" diff --git a/tests/util/test_fast_deepcopy.py b/tests/util/test_fast_deepcopy.py index 9234c6ecf..582535b2c 100644 --- a/tests/util/test_fast_deepcopy.py +++ b/tests/util/test_fast_deepcopy.py @@ -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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index eda914849..fc248edf0 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -1,17 +1,12 @@ -# -*- 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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import sys import unittest +from unittest import mock import ddt -import mock -from past.builtins import unicode import octoprint.util @@ -81,7 +76,7 @@ class BomAwareOpenTest(unittest.TestCase): def test_bom_aware_open_parameters_text_mode(self): """Tests that the parameters are propagated properly in text mode.""" - with mock.patch("io.open", wraps=io.open) as mock_open: + with mock.patch("builtins.open", wraps=open) as mock_open: with octoprint.util.bom_aware_open( self.filename_utf8_without_bom, mode="rt", @@ -163,26 +158,20 @@ class TestAtomicWrite(unittest.TestCase): pass @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move - ): + def test_atomic_write(self, mock_exists, mock_chmod, mock_ntf, mock_move): """Tests the regular basic "good" case.""" # setup - fd = 0 path = "tempfile.tmp" umask = 0o026 mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -191,27 +180,22 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="w+b") + mock_ntf.assert_called_once_with( + mode="w+b", prefix="tmp", suffix="", dir="", delete=False + ) mock_file.write.assert_called_once_with("test") mock_file.close.assert_called_once_with() mock_chmod.assert_called_once_with(path, 0o644 & ~umask) mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") - @mock.patch("os.chmod") + @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("os.chmod") # not used but needs to be mocked @mock.patch("os.path.exists") - def test_atomic_write_path_aware( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move - ): + def test_atomic_write_path_aware(self, mock_exists, mock_chmod, mock_ntf, mock_move): """Tests whether the tempoary file is to created in the same directory as the target file.""" # setup - fd = 0 tmpdirpath = "/testpath/with/subdirectories" path = os.path.join(tmpdirpath, "tempfile.tmp") targetpath = os.path.join(tmpdirpath, "somefile.yaml") @@ -219,8 +203,7 @@ class TestAtomicWrite(unittest.TestCase): mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -228,23 +211,25 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir=tmpdirpath) - mock_open.assert_called_once_with(path, mode="w+b") + mock_ntf.assert_called_once_with( + mode="w+b", + prefix="tmp", + suffix="", + dir=tmpdirpath, + delete=False, + ) mock_move.assert_called_once_with(path, targetpath) @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") - @mock.patch("os.chmod") + @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("os.chmod") # not used but needs to be mocked @mock.patch("os.path.exists") def test_atomic_write_rel_path_aware( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move + self, mock_exists, mock_chmod, mock_ntf, mock_move ): """Tests whether the tempoary file is to created in the same directory as the target file. This time submitting a relative path. """ # setup - fd = 0 tmpdirpath = "../test" path = os.path.join(tmpdirpath, "tempfile.tmp") targetpath = os.path.join(tmpdirpath, "somefile.yaml") @@ -252,8 +237,7 @@ class TestAtomicWrite(unittest.TestCase): mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -261,31 +245,32 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir=tmpdirpath) - mock_open.assert_called_once_with(path, mode="w+b") + mock_ntf.assert_called_once_with( + mode="w+b", + prefix="tmp", + suffix="", + dir=tmpdirpath, + delete=False, + ) mock_move.assert_called_once_with(path, targetpath) @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") def test_atomic_write_error_on_write( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move + self, mock_exists, mock_chmod, mock_ntf, mock_move ): """Tests the error case where something in the wrapped code fails.""" # setup - fd = 0 path = "tempfile.tmp" mock_file = mock.MagicMock() mock_file.name = path mock_file.write.side_effect = RuntimeError() - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -297,32 +282,28 @@ class TestAtomicWrite(unittest.TestCase): pass # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="w+b") + mock_ntf.assert_called_once_with( + mode="w+b", prefix="tmp", suffix="", dir="", delete=False + ) mock_file.close.assert_called_once_with() self.assertFalse(mock_move.called) self.assertFalse(mock_chmod.called) @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") def test_atomic_write_error_on_move( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move + self, mock_exists, mock_chmod, mock_ntf, mock_move ): """Tests the error case where the final move fails.""" # setup - fd = 0 path = "tempfile.tmp" mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_move.side_effect = RuntimeError() mock_exists.return_value = False @@ -335,34 +316,28 @@ class TestAtomicWrite(unittest.TestCase): pass # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="w+b") + mock_ntf.assert_called_once_with( + mode="w+b", prefix="tmp", suffix="", dir="", delete=False + ) mock_file.close.assert_called_once_with() self.assertTrue(mock_move.called) self.assertTrue(mock_chmod.called) @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write_parameters( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move - ): + def test_atomic_write_parameters(self, mock_exists, mock_chmod, mock_ntf, mock_move): """Tests that the open parameters are propagated properly.""" # setup - fd = 0 path = "tempfile.tmp" umask = 0o026 mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -373,33 +348,29 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="foo", suffix="bar", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="w", encoding="utf-8") + mock_ntf.assert_called_once_with( + mode="w", prefix="foo", suffix="bar", dir="", delete=False, encoding="utf-8" + ) mock_file.close.assert_called_once_with() mock_chmod.assert_called_once_with(path, 0o664 & ~umask) mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") def test_atomic_write_custom_permissions( - self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move + self, mock_exists, mock_chmod, mock_ntf, mock_move ): """Tests that custom permissions may be set.""" # setup - fd = 0 path = "tempfile.tmp" mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = False # test @@ -409,17 +380,15 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") + mock_ntf.assert_called_once_with( + mode="wt", prefix="tmp", suffix="", dir="", delete=False, encoding="utf-8" + ) mock_file.close.assert_called_once_with() mock_chmod.assert_called_once_with(path, 0o755) mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") @mock.patch("os.stat") @@ -428,22 +397,18 @@ class TestAtomicWrite(unittest.TestCase): mock_stat, mock_exists, mock_chmod, - mock_close, - mock_open, - mock_mkstemp, + mock_ntf, mock_move, ): """Tests that the permissions of an existing file are combined with the requested permissions.""" # setup - fd = 0 path = "tempfile.tmp" mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = True mock_stat_result = mock.MagicMock() @@ -457,17 +422,15 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") + mock_ntf.assert_called_once_with( + mode="wt", prefix="tmp", suffix="", dir="", delete=False, encoding="utf-8" + ) mock_file.close.assert_called_once_with() mock_chmod.assert_called_once_with(path, 0o777) # 0o755 | 0o666 mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.mkstemp") - @mock.patch("io.open") - @mock.patch("os.close") + @mock.patch("tempfile.NamedTemporaryFile") @mock.patch("os.chmod") @mock.patch("os.path.exists") @mock.patch("os.stat") @@ -476,22 +439,18 @@ class TestAtomicWrite(unittest.TestCase): mock_stat, mock_exists, mock_chmod, - mock_close, - mock_open, - mock_mkstemp, + mock_ntf, mock_move, ): """Tests that max_permissions limit the combined file permissions.""" # setup - fd = 0 path = "tempfile.tmp" mock_file = mock.MagicMock() mock_file.name = path - mock_mkstemp.return_value = fd, path - mock_open.return_value = mock_file + mock_ntf.return_value = mock_file mock_exists.return_value = True mock_stat_result = mock.MagicMock() @@ -505,13 +464,13 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="", dir="") - mock_close.assert_called_once_with(fd) - mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") + mock_ntf.assert_called_once_with( + mode="wt", prefix="tmp", suffix="", dir="", delete=False, encoding="utf-8" + ) mock_file.close.assert_called_once_with() mock_chmod.assert_called_once_with( path, 0o644 - ) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666 + ) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666 = 0o644 mock_move.assert_called_once_with(path, "somefile.yaml") @@ -589,7 +548,7 @@ class IsHiddenPathTest(unittest.TestCase): "path_always_hidden", ): path = getattr(self, attr) - with io.open(path, "wt+", encoding="utf-8") as f: + with open(path, "wt+", encoding="utf-8") as f: f.write(attr) if sys.platform == "win32": @@ -597,9 +556,7 @@ class IsHiddenPathTest(unittest.TestCase): # only hidden on windows import ctypes - ctypes.windll.kernel32.SetFileAttributesW( - unicode(self.path_hidden_on_windows), 2 - ) + ctypes.windll.kernel32.SetFileAttributesW(str(self.path_hidden_on_windows), 2) def tearDown(self): import shutil @@ -616,45 +573,3 @@ class IsHiddenPathTest(unittest.TestCase): def test_is_hidden_path(self, path_id, expected): path = getattr(self, path_id) if path_id is not None else None self.assertEqual(octoprint.util.is_hidden_path(path), expected) - - -try: - from glob import escape # noqa: F401 - -except ImportError: - # no glob.escape - tests for our ported implementation - - @ddt.ddt - class GlobEscapeTest(unittest.TestCase): - """ - Ported from Python 3.4 - - See https://github.com/python/cpython/commit/fd32fffa5ada8b8be8a65bd51b001d989f99a3d3 - """ - - @ddt.data( - ("abc", "abc"), - ("[", "[[]"), - ("?", "[?]"), - ("*", "[*]"), - ("[[_/*?*/_]]", "[[][[]_/[*][?][*]/_]]"), - ("/[[_/*?*/_]]/", "/[[][[]_/[*][?][*]/_]]/"), - ) - @ddt.unpack - def test_glob_escape(self, text, expected): - actual = octoprint.util.glob_escape(text) - self.assertEqual(actual, expected) - - @ddt.data( - ("?:?", "?:[?]"), - ("*:*", "*:[*]"), - (r"\\?\c:\?", r"\\?\c:\[?]"), - (r"\\*\*\*", r"\\*\*\[*]"), - ("//?/c:/?", "//?/c:/[?]"), - ("//*/*/*", "//*/*/[*]"), - ) - @ddt.unpack - @unittest.skipUnless(sys.platform == "win32", "Win32 specific test") - def test_glob_escape_windows(self, text, expected): - actual = octoprint.util.glob_escape(text) - self.assertEqual(actual, expected) diff --git a/tests/util/test_files.py b/tests/util/test_files.py index cf3b35677..b5f41853a 100644 --- a/tests/util/test_files.py +++ b/tests/util/test_files.py @@ -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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/test_jinja.py b/tests/util/test_jinja.py index 464f6a710..7d45f84b2 100644 --- a/tests/util/test_jinja.py +++ b/tests/util/test_jinja.py @@ -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) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/test_misc.py b/tests/util/test_misc.py index 86c195b3e..d999c629e 100644 --- a/tests/util/test_misc.py +++ b/tests/util/test_misc.py @@ -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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/tests/util/test_net.py b/tests/util/test_net.py index 0003194c9..6d67f2fff 100644 --- a/tests/util/test_net.py +++ b/tests/util/test_net.py @@ -1,14 +1,11 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, unicode_literals - __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 socket import unittest +from unittest import mock import ddt -import mock import octoprint.util.net diff --git a/tests/util/test_pip.py b/tests/util/test_pip.py index 9ddc5c7fe..2d480e0ee 100644 --- a/tests/util/test_pip.py +++ b/tests/util/test_pip.py @@ -1,16 +1,12 @@ -# -*- 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" -import io import os import site import unittest +from unittest import mock import ddt -import mock import pkg_resources import octoprint.util.pip @@ -161,10 +157,8 @@ class PipUtilTest(unittest.TestCase): ) def _get_lines(self, file): - with io.open(os.path.join(self._test_data, file), "r", encoding="utf-8") as f: - lines = list( - map(lambda x: x.rstrip(), f.readlines()) - ) # not str.rstrip because in py2 it'll be unicode... + with open(os.path.join(self._test_data, file), encoding="utf-8") as f: + lines = list(map(str.rstrip, f.readlines())) return lines @ddt.data( diff --git a/tests/util/test_platform.py b/tests/util/test_platform.py index 520d62911..f41a3e9ad 100644 --- a/tests/util/test_platform.py +++ b/tests/util/test_platform.py @@ -1,13 +1,10 @@ -# -*- 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) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License" import unittest +from unittest import mock import ddt -import mock @ddt.ddt diff --git a/tests/util/test_repeated_timer.py b/tests/util/test_repeated_timer.py index 8247f54f8..afcbcf507 100644 --- a/tests/util/test_repeated_timer.py +++ b/tests/util/test_repeated_timer.py @@ -1,19 +1,15 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 time import unittest - -import mock +from unittest import mock from octoprint.util import RepeatedTimer -class Countdown(object): +class Countdown: def __init__(self, start): self._counter = start diff --git a/tests/util/test_resettable_timer.py b/tests/util/test_resettable_timer.py index 569419972..e3e6e8525 100644 --- a/tests/util/test_resettable_timer.py +++ b/tests/util/test_resettable_timer.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - __author__ = "Gina Häußge " __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 time import unittest - -import mock +from unittest import mock from octoprint.util import ResettableTimer diff --git a/tests/util/test_string_helpers.py b/tests/util/test_string_helpers.py index 83bc18f4f..84343a9ed 100644 --- a/tests/util/test_string_helpers.py +++ b/tests/util/test_string_helpers.py @@ -1,77 +1,77 @@ -# -*- 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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" import unittest -from past.builtins import unicode - import octoprint.util class StringHelperTest(unittest.TestCase): - def test_to_unicode_unicode(self): - result = octoprint.util.to_unicode("test") + def test_to_str_unicode(self): + result = octoprint.util.to_str("test") self.assertEqual(result, "test") - self.assertIsInstance(result, unicode) + self.assertIsInstance(result, str) - def test_to_unicode_bytes(self): - result = octoprint.util.to_unicode(b"test") + def test_to_str_bytes(self): + result = octoprint.util.to_str(b"test") self.assertEqual(result, "test") - self.assertIsInstance(result, unicode) + self.assertIsInstance(result, str) - def test_to_unicode_bytes_utf8(self): + def test_to_str_bytes_utf8(self): data = "äöüß" - result = octoprint.util.to_unicode(data.encode("utf-8"), encoding="utf-8") + result = octoprint.util.to_str(data.encode("utf-8"), encoding="utf-8") self.assertEqual(result, data) - self.assertIsInstance(result, unicode) + self.assertIsInstance(result, str) - def test_to_unicode_bytes_utf8_vs_ascii(self): + def test_to_str_bytes_utf8_vs_ascii(self): self.assertRaises( UnicodeDecodeError, - octoprint.util.to_unicode, - "äöüß".encode("utf-8"), + octoprint.util.to_str, + "äöüß".encode(), encoding="ascii", ) - def test_to_unicode_bytes_utf8_vs_ascii_replace(self): + def test_to_str_bytes_utf8_vs_ascii_replace(self): data = "äöüß" - result = octoprint.util.to_unicode( + result = octoprint.util.to_str( data.encode("utf-8"), encoding="ascii", errors="replace" ) self.assertEqual(result, data.encode("utf-8").decode("ascii", errors="replace")) - self.assertIsInstance(result, unicode) + self.assertIsInstance(result, str) def test_to_bytes_bytes(self): result = octoprint.util.to_bytes(b"test") self.assertEqual(result, b"test") self.assertIsInstance(result, bytes) - def test_to_bytes_unicode(self): + def test_to_bytes_str(self): result = octoprint.util.to_bytes("test") self.assertEqual(result, b"test") self.assertIsInstance(result, bytes) - def test_to_bytes_unicode_utf8(self): + def test_to_bytes_str_utf8(self): data = "äöüß" result = octoprint.util.to_bytes(data, encoding="utf-8") self.assertEqual(result, data.encode("utf-8")) self.assertIsInstance(result, bytes) - def test_to_bytes_unicode_utf8_vs_ascii(self): + def test_to_bytes_str_utf8_vs_ascii(self): self.assertRaises( UnicodeEncodeError, octoprint.util.to_bytes, "äöüß", encoding="ascii" ) - def test_to_bytes_unicode_utf8_vs_ascii_replace(self): + def test_to_bytes_str_utf8_vs_ascii_replace(self): data = "äöüß" result = octoprint.util.to_bytes(data, encoding="ascii", errors="replace") self.assertEqual(result, data.encode("ascii", errors="replace")) self.assertIsInstance(result, bytes) - def test_to_str_still_works(self): - result = octoprint.util.to_str("test") - self.assertEqual(result, b"test") - self.assertIsInstance(result, bytes) + def test_to_unicode(self): + result = octoprint.util.to_unicode(b"test") + self.assertEqual(result, "test") + self.assertIsInstance(result, str) + + def test_to_native_str(self): + result = octoprint.util.to_native_str(b"test") + self.assertEqual(result, "test") + self.assertIsInstance(result, str) diff --git a/tests/util/test_version.py b/tests/util/test_version.py index 59df747ea..64d26fab4 100644 --- a/tests/util/test_version.py +++ b/tests/util/test_version.py @@ -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) 2021 The OctoPrint Project - Released under terms of the AGPLv3 License" diff --git a/versioneer.py b/versioneer.py index 46342e84f..a2e6dfdeb 100644 --- a/versioneer.py +++ b/versioneer.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # flake8: noqa -from __future__ import absolute_import, division, print_function, unicode_literals # Version: 0.15+dev @@ -372,10 +370,7 @@ https://creativecommons.org/publicdomain/zero/1.0/ . """ -try: - import configparser -except ImportError: - import ConfigParser as configparser +import configparser import errno import io import json @@ -436,7 +431,7 @@ def get_config_from_root(root): # TODO: find a py2 compatible solution for the configparser deprecation issues parser = configparser.SafeConfigParser() - with io.open(setup_cfg, "rt", encoding="utf-8") as f: + with open(setup_cfg, encoding="utf-8") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory @@ -494,7 +489,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 @@ -504,7 +499,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): return None else: if verbose: - print("unable to find command, tried {}".format(commands)) + print(f"unable to find command, tried {commands}") return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: @@ -1226,7 +1221,7 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = io.open(versionfile_abs, "rt", encoding="utf-8") + f = open(versionfile_abs, encoding="utf-8") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) @@ -1237,7 +1232,7 @@ def git_get_keywords(versionfile_abs): if mo: keywords["full"] = mo.group(1) f.close() - except EnvironmentError: + except OSError: pass return keywords @@ -1420,7 +1415,7 @@ def git_parse_lookup_file(path): import re lookup = [] - with io.open(path, "r") as f: + with open(path) as f: for line in f: if "#" in line: line = line[: line.index("#")] @@ -1538,16 +1533,16 @@ def do_vcs_install(manifest_in, versionfile_source, ipy): files.append(versioneer_file) present = False try: - f = io.open(".gitattributes", "rt", encoding="utf-8") + f = open(".gitattributes", encoding="utf-8") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() - except EnvironmentError: + except OSError: pass if not present: - f = io.open(".gitattributes", "a+t", encoding="utf-8") + f = open(".gitattributes", "a+t", encoding="utf-8") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") @@ -1597,9 +1592,9 @@ def get_versions(): def versions_from_file(filename): try: - with io.open(filename, "rt", encoding="utf-8") as f: + with open(filename, encoding="utf-8") as f: contents = f.read() - except EnvironmentError: + except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search( r"version_json = '''\s+(.*)''' # END VERSION_JSON", contents, re.M | re.S @@ -1612,7 +1607,7 @@ def versions_from_file(filename): def write_to_version_file(filename, versions): os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) - with io.open(filename, "wt", encoding="utf-8") as f: + with open(filename, "wt", encoding="utf-8") as f: f.write(SHORT_VERSION_PY % contents) print("set {} to '{}'".format(filename, versions["version"])) @@ -1890,7 +1885,7 @@ def get_versions(verbose=False): try: ver = versions_from_file(versionfile_abs) if verbose: - print("got version from file {} {}".format(versionfile_abs, ver)) + print(f"got version from file {versionfile_abs} {ver}") return ver except NotThisMethod: pass @@ -2033,7 +2028,7 @@ def get_cmdclass(): _build_exe.run(self) os.unlink(target_versionfile) - with io.open(cfg.versionfile_source, "wt", encoding="utf-8") as f: + with open(cfg.versionfile_source, "wt", encoding="utf-8") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG @@ -2129,20 +2124,16 @@ def do_setup(): root = get_root() try: cfg = get_config_from_root(root) - except ( - EnvironmentError, - configparser.NoSectionError, - configparser.NoOptionError, - ) as e: + except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) - with io.open(os.path.join(root, "setup.cfg"), "at", encoding="utf-8") as f: + with open(os.path.join(root, "setup.cfg"), "at", encoding="utf-8") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) - with io.open(cfg.versionfile_source, "wt", encoding="utf-8") as f: + with open(cfg.versionfile_source, "wt", encoding="utf-8") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write( LONG @@ -2159,13 +2150,13 @@ def do_setup(): ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: - with io.open(ipy, "rt", encoding="utf-8") as f: + with open(ipy, encoding="utf-8") as f: old = f.read() - except EnvironmentError: + except OSError: old = "" if "from ._version import get_versions" not in old: print(" appending to %s" % ipy) - with io.open(ipy, "at", encoding="utf-8") as f: + with open(ipy, "at", encoding="utf-8") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) @@ -2180,12 +2171,12 @@ def do_setup(): manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: - with io.open(manifest_in, "r") as f: + with open(manifest_in) as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) - except EnvironmentError: + except OSError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so @@ -2193,7 +2184,7 @@ def do_setup(): # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") - with io.open(manifest_in, "at", encoding="utf-8") as f: + with open(manifest_in, "at", encoding="utf-8") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") @@ -2201,7 +2192,7 @@ def do_setup(): print( " appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source ) - with io.open(manifest_in, "at", encoding="utf-8") as f: + with open(manifest_in, "at", encoding="utf-8") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") @@ -2217,7 +2208,7 @@ def scan_setup_py(): found = set() setters = False errors = 0 - with io.open("setup.py", "rt", encoding="utf-8") as f: + with open("setup.py", encoding="utf-8") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import")