Merge pull request #1604 from clinton-hall/fix/flake8

Fix/flake8
This commit is contained in:
Labrys of Knossos 2019-04-07 13:51:51 -04:00 committed by GitHub
commit e4b03005a1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 122 additions and 108 deletions

View file

@ -1,16 +1,15 @@
#!/usr/bin/env python
# coding=utf-8
import eol
eol.check()
import cleanup
cleanup.clean(cleanup.FOLDER_STRUCTURE)
import datetime
import os
import sys
import eol
import cleanup
eol.check()
cleanup.clean(cleanup.FOLDER_STRUCTURE)
import core
from core import logger, main_db
from core.auto_process import comics, games, movies, music, tv, books
@ -18,7 +17,11 @@ from core.auto_process.common import ProcessResult
from core.plugins.plex import plex_update
from core.user_scripts import external_script
from core.utils import char_replace, convert_to_ascii, replace_links
from six import text_type
try:
text_type = unicode
except NameError:
text_type = str
def process_torrent(input_directory, input_name, input_category, input_hash, input_id, client_agent):
@ -259,7 +262,6 @@ def process_torrent(input_directory, input_name, input_category, input_hash, inp
elif section_name == 'LazyLibrarian':
result = books.process(section_name, output_destination, input_name, status, client_agent, input_category)
plex_update(input_category)
if result.status_code != 0:
@ -279,7 +281,7 @@ def process_torrent(input_directory, input_name, input_category, input_hash, inp
# remove torrent
if core.USE_LINK == 'move-sym' and not core.DELETE_ORIGINAL == 1:
logger.debug('Checking for sym-links to re-direct in: {0}'.format(input_directory))
for dirpath, dirs, files in os.walk(input_directory):
for dirpath, _, files in os.walk(input_directory):
for file in files:
logger.debug('Checking symlink: {0}'.format(os.path.join(dirpath, file)))
replace_links(os.path.join(dirpath, file))

View file

@ -25,6 +25,7 @@ FOLDER_STRUCTURE = {
class WorkingDirectory(object):
"""Context manager for changing current working directory."""
def __init__(self, new, original=None):
self.working_directory = new
self.original_directory = os.getcwd() if original is None else original
@ -43,7 +44,7 @@ class WorkingDirectory(object):
original_directory=self.original_directory,
error=error,
working_directory=self.working_directory,
)
),
)

4
eol.py
View file

@ -157,7 +157,7 @@ def print_statuses(show_expired=False):
major=python_version[0],
minor=python_version[1],
remaining=days_left,
)
),
)
if not show_expired:
return
@ -171,7 +171,7 @@ def print_statuses(show_expired=False):
major=python_version[0],
minor=python_version[1],
remaining=-days_left,
)
),
)

View file

@ -1,7 +1,8 @@
# coding=utf-8
"""A synchronous implementation of the Deluge RPC protocol
based on gevent-deluge by Christopher Rosell.
"""
A synchronous implementation of the Deluge RPC protocol.
Based on gevent-deluge by Christopher Rosell:
https://github.com/chrippa/gevent-deluge
Example usage:
@ -18,6 +19,6 @@ Example usage:
from .exceptions import DelugeRPCError
__title__ = "synchronous-deluge"
__version__ = "0.1"
__author__ = "Christian Dale"
__title__ = 'synchronous-deluge'
__version__ = '0.1'
__author__ = 'Christian Dale'

View file

@ -9,7 +9,7 @@ from .exceptions import DelugeRPCError
from .protocol import DelugeRPCRequest, DelugeRPCResponse
from .transfer import DelugeTransfer
__all__ = ["DelugeClient"]
__all__ = ['DelugeClient']
RPC_RESPONSE = 1
RPC_ERROR = 2
@ -18,41 +18,41 @@ RPC_EVENT = 3
class DelugeClient(object):
def __init__(self):
"""A deluge client session."""
"""Create a deluge client session."""
self.transfer = DelugeTransfer()
self.modules = []
self._request_counter = 0
def _get_local_auth(self):
username = password = ""
username = password = ''
if platform.system() in ('Windows', 'Microsoft'):
app_data_path = os.environ.get("APPDATA")
app_data_path = os.environ.get('APPDATA')
if not app_data_path:
from six.moves import winreg
hkey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
)
app_data_reg = winreg.QueryValueEx(hkey, "AppData")
app_data_reg = winreg.QueryValueEx(hkey, 'AppData')
app_data_path = app_data_reg[0]
winreg.CloseKey(hkey)
auth_file = os.path.join(app_data_path, "deluge", "auth")
auth_file = os.path.join(app_data_path, 'deluge', 'auth')
else:
from xdg.BaseDirectory import save_config_path
try:
auth_file = os.path.join(save_config_path("deluge"), "auth")
auth_file = os.path.join(save_config_path('deluge'), 'auth')
except OSError:
return username, password
if os.path.exists(auth_file):
for line in open(auth_file):
if line.startswith("#"):
if line.startswith('#'):
# This is a comment line
continue
line = line.strip()
try:
lsplit = line.split(":")
lsplit = line.split(':')
except Exception:
continue
@ -63,13 +63,13 @@ class DelugeClient(object):
else:
continue
if username == "localclient":
if username == 'localclient':
return username, password
return "", ""
return '', ''
def _create_module_method(self, module, method):
fullname = "{0}.{1}".format(module, method)
fullname = '{0}.{1}'.format(module, method)
def func(obj, *args, **kwargs):
return self.remote_call(fullname, *args, **kwargs)
@ -80,18 +80,18 @@ class DelugeClient(object):
def _introspect(self):
def splitter(value):
return value.split(".")
return value.split('.')
self.modules = []
methods = self.remote_call("daemon.get_method_list").get()
methods = self.remote_call('daemon.get_method_list').get()
methodmap = defaultdict(dict)
for module, method in imap(splitter, methods):
methodmap[module][method] = self._create_module_method(module, method)
for module, methods in methodmap.items():
clsname = "DelugeModule{0}".format(module.capitalize())
clsname = 'DelugeModule{0}'.format(module.capitalize())
cls = type(clsname, (), methods)
setattr(self, module, cls())
self.modules.append(module)
@ -133,24 +133,23 @@ class DelugeClient(object):
self._request_counter += 1
return response
def connect(self, host="127.0.0.1", port=58846, username="", password=""):
"""Connects to a daemon process.
def connect(self, host='127.0.0.1', port=58846, username='', password=''):
"""Connect to a daemon process.
:param host: str, the hostname of the daemon
:param port: int, the port of the daemon
:param username: str, the username to login with
:param password: str, the password to login with
"""
# Connect transport
self.transfer.connect((host, port))
# Attempt to fetch local auth info if needed
if not username and host in ("127.0.0.1", "localhost"):
if not username and host in ('127.0.0.1', 'localhost'):
username, password = self._get_local_auth()
# Authenticate
self.remote_call("daemon.login", username, password).get()
self.remote_call('daemon.login', username, password).get()
# Introspect available methods
self._introspect()

View file

@ -8,4 +8,4 @@ class DelugeRPCError(Exception):
self.traceback = traceback
def __str__(self):
return "{0}: {1}: {2}".format(self.__class__.__name__, self.name, self.msg)
return '{0}: {1}: {2}'.format(self.__class__.__name__, self.name, self.msg)

View file

@ -6,7 +6,7 @@ import zlib
import rencode
__all__ = ["DelugeTransfer"]
__all__ = ['DelugeTransfer']
class DelugeTransfer(object):
@ -33,7 +33,7 @@ class DelugeTransfer(object):
payload = zlib.compress(rencode.dumps(data))
self.conn.sendall(payload)
buf = b""
buf = b''
while True:
data = self.conn.recv(1024)

View file

@ -31,8 +31,7 @@ class UTorrentClient(object):
# TODO refresh token, when necessary
def _make_opener(self, realm, base_url, username, password):
"""uTorrent API need HTTP Basic Auth and cookie support for token verify."""
"""HTTP Basic Auth and cookie support for token verification."""
auth_handler = HTTPBasicAuthHandler()
auth_handler.add_password(realm=realm,
uri=base_url,
@ -61,25 +60,25 @@ class UTorrentClient(object):
return self._action(params)
def start(self, *hashes):
params = [('action', 'start'), ]
params = [('action', 'start')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)
def stop(self, *hashes):
params = [('action', 'stop'), ]
params = [('action', 'stop')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)
def pause(self, *hashes):
params = [('action', 'pause'), ]
params = [('action', 'pause')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)
def forcestart(self, *hashes):
params = [('action', 'forcestart'), ]
params = [('action', 'forcestart')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)
@ -95,8 +94,8 @@ class UTorrentClient(object):
def setprops(self, cur_hash, **kvpairs):
params = [('action', 'setprops'), ('hash', cur_hash)]
for k, v in iteritems(kvpairs):
params.append(("s", k))
params.append(("v", v))
params.append(('s', k))
params.append(('v', v))
return self._action(params)
@ -125,13 +124,13 @@ class UTorrentClient(object):
self._action(params)
def remove(self, *hashes):
params = [('action', 'remove'), ]
params = [('action', 'remove')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)
def removedata(self, *hashes):
params = [('action', 'removedata'), ]
params = [('action', 'removedata')]
for cur_hash in hashes:
params.append(('hash', cur_hash))
return self._action(params)

View file

@ -657,16 +657,16 @@
from __future__ import print_function
import eol
eol.check()
import cleanup
cleanup.clean(cleanup.FOLDER_STRUCTURE)
import datetime
import os
import sys
import eol
import cleanup
eol.check()
cleanup.clean(cleanup.FOLDER_STRUCTURE)
import core
from core import logger, main_db
from core.auto_process import comics, games, movies, music, tv, books

16
tox.ini
View file

@ -33,6 +33,15 @@ commands =
max-line-length = 79
verbose = 2
statistics = True
exclude =
.github/
.tox/
.pytest_cache/
htmlcov/
logs/
libs/common
libs/win
libs/py2
ignore =
; -- flake8 --
; E501 line too long
@ -57,10 +66,13 @@ ignore =
per-file-ignores =
; F401 imported but unused
; E402 module level import not at top of file
nzbTo*.py: E265, E266, E402
TorrentToMedia.py: E402
core/__init__.py: E402, F401
core/utils/__init__.py: F401
core/plugins/downloaders/configuration.py: F401
core/plugins/downloaders/utils.py: F401
libs/custom/synchronousdeluge/__init__.py: F401
[testenv:check]
deps =
@ -74,13 +86,13 @@ skip_install = true
commands =
; ** PRIMARY TESTS **
; Run flake8 tests (with plugins) using default test selections
flake8 core tests setup.py
flake8
; ** SELECTIVE TESTS **
; Run flake8 tests (with plugins) for specific optional codes defined below
; -- flake8-bugbear --
; B902 Invalid first argument used for instance method.
; B903 Data class should be immutable or use __slots__ to save memory.
flake8 core tests setup.py --select=B902,B903
flake8 --select=B902,B903
[coverage:run]
omit =