Fixed LGTM errors and warnings

This commit is contained in:
Fabio Manganiello 2021-09-17 00:47:33 +02:00
parent 8c31905534
commit 7b8938cb12
11 changed files with 24 additions and 22 deletions

View File

@ -29,9 +29,11 @@ Guidelines:
- If the feature requires an optional dependency then make sure to document it: - If the feature requires an optional dependency then make sure to document it:
- In the class docstring (see other plugins and backends for examples) - In the class docstring (see other plugins and backends for examples).
- In [`setup.py`](https://git.platypush.tech/platypush/platypush/-/blob/master/setup.py#L72) as - In [`setup.py`](https://git.platypush.tech/platypush/platypush/-/blob/master/setup.py#L72) as
an `extras_require` entry an `extras_require` entry.
- In [`requirements.txt`](https://git.platypush.tech/platypush/platypush/-/blob/master/requirements.txt) - - In the plugin/backend class pydoc string.
if the feature is optional then leave it commented and add a one-line comment to explain which - In the `manifest.yaml` - refer to the Wiki (how to write
plugin or backend requires it. [plugins](https://git.platypush.tech/platypush/platypush/-/wikis/writing-your-own-plugins)
and [backends](https://git.platypush.tech/platypush/platypush/-/wikis/writing-your-own-backends))
for examples on how to write an extension manifest file.

View File

@ -1,6 +1,6 @@
import json import json
from flask import abort, request, Response, Blueprint from flask import abort, request, Response, Blueprint, escape
from platypush.backend.http.app import template_folder from platypush.backend.http.app import template_folder
from platypush.common.spotify import SpotifyMixin from platypush.common.spotify import SpotifyMixin
@ -31,7 +31,7 @@ def auth_callback():
get_redis().rpush(SpotifyMixin.get_spotify_queue_for_state(state), json.dumps(msg)) get_redis().rpush(SpotifyMixin.get_spotify_queue_for_state(state), json.dumps(msg))
if error: if error:
return Response(f'Authentication failed: {error}') return Response(f'Authentication failed: {escape(error)}')
return Response('Authentication successful. You can now close this window') return Response('Authentication successful. You can now close this window')

View File

@ -1,3 +1,4 @@
import logging
import time import time
from typing import Callable, Optional from typing import Callable, Optional
@ -16,6 +17,7 @@ class Listener(_Listener):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._on_open_hndl = on_open self._on_open_hndl = on_open
self._on_close_hndl = on_close self._on_close_hndl = on_close
self.logger = logging.getLogger(__name__)
def _on_open(self): def _on_open(self):
def callback(*_): def callback(*_):
@ -30,11 +32,10 @@ class Listener(_Listener):
def callback(*_): def callback(*_):
self.connected = False self.connected = False
if self._on_close_hndl: if self._on_close_hndl:
# noinspection PyBroadException
try: try:
self._on_close_hndl() self._on_close_hndl()
except: except Exception as e:
pass self.logger.warning(f'Pushbullet listener close error: {e}')
return callback return callback

View File

@ -23,7 +23,7 @@ class SlackEvent(Event, ABCMeta):
if not (isinstance(timestamp, int) or isinstance(timestamp, float)): if not (isinstance(timestamp, int) or isinstance(timestamp, float)):
return timestamp return timestamp
return datetime.fromtimestamp(timestamp, tz=gettz()) return datetime.fromtimestamp(timestamp, tz=gettz()) # lgtm [py/call-to-non-callable]
class SlackMessageEvent(SlackEvent, ABCMeta): class SlackMessageEvent(SlackEvent, ABCMeta):

View File

@ -87,11 +87,10 @@ class RunnablePlugin(Plugin):
self._should_stop.set() self._should_stop.set()
if self._thread and self._thread.is_alive(): if self._thread and self._thread.is_alive():
self.logger.info(f'Waiting for {self.__class__.__name__} to stop') self.logger.info(f'Waiting for {self.__class__.__name__} to stop')
# noinspection PyBroadException
try: try:
self._thread.join() self._thread.join()
except: except Exception as e:
pass self.logger.warning(f'Could not join thread on stop: {e}')
self.logger.info(f'{self.__class__.__name__} stopped') self.logger.info(f'{self.__class__.__name__} stopped')

View File

@ -80,7 +80,7 @@ class OtpPlugin(Plugin):
os.makedirs(os.path.dirname(os.path.abspath(os.path.expanduser(secret_path))), exist_ok=True) os.makedirs(os.path.dirname(os.path.abspath(os.path.expanduser(secret_path))), exist_ok=True)
secret = pyotp.random_base32() secret = pyotp.random_base32()
with open(secret_path, 'w') as f: with open(secret_path, 'w') as f:
f.writelines([secret]) f.writelines([secret]) # lgtm [py/clear-text-storage-sensitive-data]
os.chmod(secret_path, 0o600) os.chmod(secret_path, 0o600)
return secret return secret

View File

@ -39,7 +39,7 @@ class PiholePlugin(Plugin):
def _get_token(password: Optional[str] = None, api_key: Optional[str] = None) -> str: def _get_token(password: Optional[str] = None, api_key: Optional[str] = None) -> str:
if not password: if not password:
return api_key or '' return api_key or ''
return hashlib.sha256(hashlib.sha256(str(password).encode()).hexdigest().encode()).hexdigest() return hashlib.sha256(hashlib.sha256(str(password).encode()).hexdigest().encode()).hexdigest() # lgtm [py/weak-sensitive-data-hashing]
def _get_url(self, name: str, server: Optional[str] = None, password: Optional[str] = None, def _get_url(self, name: str, server: Optional[str] = None, password: Optional[str] = None,
ssl: Optional[bool] = None, api_key: Optional[str] = None, **kwargs) -> str: ssl: Optional[bool] = None, api_key: Optional[str] = None, **kwargs) -> str:
@ -116,10 +116,10 @@ class PiholePlugin(Plugin):
try: try:
status = (response.json() or {}).get('status') status = (response.json() or {}).get('status')
assert status == 'enabled', 'Wrong credentials'
except Exception as e: except Exception as e:
raise AssertionError('Could not enable the server: {}'.format(response.text or str(e))) raise AssertionError('Could not enable the server: {}'.format(response.text or str(e)))
assert status == 'enabled', 'Could not enable the server: Wrong credentials'
return response.json() return response.json()
@action @action
@ -143,10 +143,10 @@ class PiholePlugin(Plugin):
try: try:
status = (response.json() or {}).get('status') status = (response.json() or {}).get('status')
assert status == 'disabled', 'Wrong credentials'
except Exception as e: except Exception as e:
raise AssertionError('Could not disable the server: {}'.format(response.text or str(e))) raise AssertionError('Could not disable the server: {}'.format(response.text or str(e)))
assert status == 'disabled', 'Could not disable the server: Wrong credentials'
return response.json() return response.json()
def _list_manage(self, domain: str, list_name: str, endpoint: str, server: Optional[str] = None, def _list_manage(self, domain: str, list_name: str, endpoint: str, server: Optional[str] = None,

View File

@ -143,7 +143,7 @@ class SlackPlugin(ChatPlugin, RunnablePlugin):
try: try:
rs.raise_for_status() rs.raise_for_status()
except: except: # lgtm [py/catch-base-exception]
if rs.status_code == 401 or rs.status_code == 403: if rs.status_code == 401 or rs.status_code == 403:
self.logger.error('Unauthorized/Forbidden Slack API request, stopping the service') self.logger.error('Unauthorized/Forbidden Slack API request, stopping the service')
self.stop() self.stop()

View File

@ -8,7 +8,7 @@ from platypush.plugins.bluetooth.ble import BluetoothBlePlugin
from platypush.plugins.switch import SwitchPlugin from platypush.plugins.switch import SwitchPlugin
class SwitchbotBluetoothPlugin(SwitchPlugin, BluetoothBlePlugin): class SwitchbotBluetoothPlugin(SwitchPlugin, BluetoothBlePlugin): # lgtm [py/missing-call-to-init]
""" """
Plugin to interact with a Switchbot (https://www.switch-bot.com/) device and Plugin to interact with a Switchbot (https://www.switch-bot.com/) device and
programmatically control switches over a Bluetooth interface. programmatically control switches over a Bluetooth interface.

View File

@ -9,7 +9,7 @@ from platypush.plugins.mqtt import MqttPlugin, action
from platypush.plugins.switch import SwitchPlugin from platypush.plugins.switch import SwitchPlugin
class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin): class ZigbeeMqttPlugin(MqttPlugin, SwitchPlugin): # lgtm [py/missing-call-to-init]
""" """
This plugin allows you to interact with Zigbee devices over MQTT through any Zigbee sniffer and This plugin allows you to interact with Zigbee devices over MQTT through any Zigbee sniffer and
`zigbee2mqtt <https://www.zigbee2mqtt.io/>`_. `zigbee2mqtt <https://www.zigbee2mqtt.io/>`_.

View File

@ -4,7 +4,7 @@ from typing import Optional
from marshmallow import fields from marshmallow import fields
class StrippedString(fields.Function): class StrippedString(fields.Function): # lgtm [py/missing-call-to-init]
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
kwargs['serialize'] = self._strip kwargs['serialize'] = self._strip
kwargs['deserialize'] = self._strip kwargs['deserialize'] = self._strip