♻️ Migrate code base to Python 3 only
* pyupgrade
* various new codemods
* manual removal of Py2/3 compat imports
* manual adjustment of docs, examples, tests
* to_str is now the new to_unicode, deprecated
redirection to to_bytes has been removed
* to_native_str has been redirected to point to
to_str
* to_unicode has been redirected to point to
to_str
* atomic_write refactored to use
NamedTemporaryDirectory
* various other fixes/refactorings all over the
place
This commit is contained in:
1 parent
853e7f0765
commit
7fb9df9940
206 files changed
+1528
-5389
No files matched your search
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -14,7 +14,7 @@ below.
|
||||
|
||||
* Prerequisites:
|
||||
|
||||
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Latest stable Python 3 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
|
||||
* `Git <https://git-scm.com>`_
|
||||
|
||||
* 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 <https://python.org>`_ 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 <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
|
||||
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 <https://octoprint.org/files/python-2.7.18.msi>`_ (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 <https://octoprint.org/files/VCForPython27.msi>`_ (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 <https://community.octoprint.org/t/setting-up-octoprint-on-macos/13425>`_.
|
||||
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 <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ 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: ``<OctoPrint venv3 folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv3 folder>/Scripts/pre-commit`` (Windows)
|
||||
* Program: ``<OctoPrint venv folder>/bin/pre-commit`` (Linux) or ``<OctoPrint venv folder>/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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
@@ -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)):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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<req>.+);\s*(?P<marker>python_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"]}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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("#")]
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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,
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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:
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
+10
-15
@@ -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)))
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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},
|
||||
)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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!")
|
||||
|
||||
@@ -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):
|
||||
|
||||
+6
-10
@@ -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):
|
||||
|
||||
@@ -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"],
|
||||
|
||||
+13
-25
@@ -1,21 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import collections
|
||||
import datetime
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
import queue
|
||||
except ImportError:
|
||||
import Queue as queue
|
||||
|
||||
import collections
|
||||
import queue
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
import octoprint.plugin
|
||||
@@ -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
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import 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()
|
||||
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import 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:
|
||||
|
||||
@@ -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"
|
||||
@@ -1,40 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import 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:
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
|
||||
@@ -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:]))
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 <osd@foosel.net>"
|
||||
__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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 <osd@foosel.net>"
|
||||
__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)
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__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"<img.*?/?>")
|
||||
@@ -529,11 +520,11 @@ _image_tag_re = re.compile(r"<img.*?/?>")
|
||||
|
||||
def _strip_images(text):
|
||||
"""
|
||||
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: "
|
||||
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"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("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback) # doctest: +ALLOW_UNICODE
|
||||
>>> _replace_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", callback)
|
||||
"<a href='test.html'>I'm a link</a> and this is an image: foobar"
|
||||
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", callback) # doctest: +ALLOW_UNICODE
|
||||
>>> _replace_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"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<quote>[\'"]*)(?P<src>.*?)(?P=quote)(?=\s+|>
|
||||
|
||||
def _lazy_images(text, placeholder=None):
|
||||
"""
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>")
|
||||
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("<a href='test.html'>I'm a link</a> and this is an image: <img src='foo.jpg' alt='foo'>", placeholder="ph.png")
|
||||
'<a href=\\'test.html\\'>I\\'m a link</a> and this is an image: <img src="ph.png" data-src=\\'foo.jpg\\' alt=\\'foo\\'>'
|
||||
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png") # doctest: +ALLOW_UNICODE
|
||||
>>> _lazy_images("One <img src=\\"one.jpg\\"> and two <img src='two.jpg' > and three <img src=three.jpg> and four <img src=\\"four.png\\" alt=\\"four\\">", placeholder="ph.png")
|
||||
'One <img src="ph.png" data-src="one.jpg"> and two <img src="ph.png" data-src=\\'two.jpg\\' > and three <img src="ph.png" data-src=three.jpg> and four <img src="ph.png" data-src="four.png" alt="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("<a href='test.html'>Hello world</a><img src='foo.jpg'>") # doctest: +ALLOW_UNICODE
|
||||
>>> _strip_tags("<a href='test.html'>Hello world</a><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__ = {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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"
|
||||
@@ -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()
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import 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
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
import datetime
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
@@ -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__():
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Haeussge <osd@foosel.net>"
|
||||
__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
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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"}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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:
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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 ""
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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):
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
@@ -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 <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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()]
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -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()
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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__():
|
||||
|
||||
@@ -1,47 +1,24 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__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_<command> 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<passcode>.
|
||||
# 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)
|
||||
|
||||
@@ -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 <osd@foosel.net>"
|
||||
__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.
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
|
||||
@@ -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 <osd@foosel.net>"
|
||||
__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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
+114
-125
@@ -1,13 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import 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}</a>".format(tag=tag, content=content)
|
||||
return f"<{tag}>{content}</a>"
|
||||
|
||||
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:
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import io
|
||||
import logging
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Marc Hannappel <salandora@gmail.com>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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...
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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)
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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)
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
@@ -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")
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import absolute_import, division, print_function, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user