beremiz

Fix various pylint and pep8 errors

2019-03-13, Andrey Skvortsov
eb4a4cc41914
Fix various pylint and pep8 errors

Check basic code-style problems for PEP-8
pep8 version: 2.4.0
./connectors/PYRO/__init__.py:57:43: E261 at least two spaces before inline comment
./connectors/SchemeEditor.py:29:21: E128 continuation line under-indented for visual indent
./controls/IDBrowser.py:101:23: E127 continuation line over-indented for visual indent
./controls/IDBrowser.py:102:23: E127 continuation line over-indented for visual indent

Check for problems using pylint ...
No config file found, using default configuration
pylint 1.9.4,
astroid 1.6.5
Python 2.7.16rc1 (default, Feb 18 2019, 11:05:09)
[GCC 8.2.0]
Use multiple threads for pylint
Using config file /home/developer/WorkData/PLC/beremiz/beremiz/.pylint
************* Module connectors.PYRO_dialog
connectors/PYRO_dialog.py:9: [W0611(unused-import), ] Unused import wx
************* Module connectors
connectors/__init__.py:32: [W1652(deprecated-types-field), ] Accessing a deprecated fields on the types module
connectors/__init__.py:32: [C0411(wrong-import-order), ] standard import "from types import ClassType" should be placed before "from connectors.ConnectorBase import ConnectorBase"
************* Module connectors.PYRO.PSK_Adapter
connectors/PYRO/PSK_Adapter.py:7: [C0411(wrong-import-order), ] standard import "import ssl" should be placed before "import sslpsk"
************* Module connectors.SchemeEditor
connectors/SchemeEditor.py:29: [C0330(bad-continuation), ] Wrong continued indentation (add 1 space).
wx.ALIGN_CENTER_VERTICAL),
^|
connectors/SchemeEditor.py:42: [W0631(undefined-loop-variable), SchemeEditor.__init__] Using possibly undefined loop variable 'tag'
************* Module runtime.WampClient
runtime/WampClient.py:138: [W1612(unicode-builtin), WampSession.onJoin] unicode built-in referenced
runtime/WampClient.py:154: [W1612(unicode-builtin), WampSession.publishWithOwnID] unicode built-in referenced
runtime/WampClient.py:346: [W1612(unicode-builtin), PublishEvent] unicode built-in referenced
runtime/WampClient.py:351: [W1612(unicode-builtin), PublishEventWithOwnID] unicode built-in referenced
runtime/WampClient.py:31: [W0611(unused-import), ] Unused str imported from builtins as text
************* Module runtime.PLCObject
runtime/PLCObject.py:35: [W1648(bad-python3-import), ] Module moved in Python 3
runtime/PLCObject.py:35: [C0411(wrong-import-order), ] standard import "import md5" should be placed before "from six.moves import xrange"
runtime/PLCObject.py:36: [C0411(wrong-import-order), ] standard import "from tempfile import mkstemp" should be placed before "from six.moves import xrange"
runtime/PLCObject.py:37: [C0411(wrong-import-order), ] standard import "import shutil" should be placed before "from six.moves import xrange"
runtime/PLCObject.py:38: [C0411(wrong-import-order), ] standard import "from functools import wraps, partial" should be placed before "from six.moves import xrange"
************* Module runtime.Worker
runtime/Worker.py:12: [W1648(bad-python3-import), ] Module moved in Python 3
************* Module runtime.spawn_subprocess
runtime/spawn_subprocess.py:125: [C0325(superfluous-parens), ] Unnecessary parens after 'print' keyword
runtime/spawn_subprocess.py:130: [C0325(superfluous-parens), ] Unnecessary parens after 'print' keyword
runtime/spawn_subprocess.py:125: [E1601(print-statement), ] print statement used
runtime/spawn_subprocess.py:130: [E1601(print-statement), ] print statement used
************* Module controls.IDBrowser
controls/IDBrowser.py:101: [C0330(bad-continuation), ] Wrong continued indentation (remove 5 spaces).
if self.isManager
| ^
controls/IDBrowser.py:102: [C0330(bad-continuation), ] Wrong continued indentation (remove 5 spaces).
else dv.DATAVIEW_CELL_INERT),
| ^
************* Module Beremiz_service
Beremiz_service.py:34: [W0611(unused-import), ] Unused import __builtin__
# jsonrpc.py
# original code: http://trac.pyworks.org/pyjamas/wiki/DjangoWithPyJamas
# also from: http://www.pimentech.fr/technologies/outils
from __future__ import absolute_import
import datetime
from builtins import str as text
from django.core.serializers import serialize
from svgui.pyjs.jsonrpc.jsonrpc import JSONRPCServiceBase
# JSONRPCService and jsonremote are used in combination to drastically
# simplify the provision of JSONRPC services. use as follows:
#
# jsonservice = JSONRPCService()
#
# @jsonremote(jsonservice)
# def test(request, echo_param):
# return "echoing the param back: %s" % echo_param
#
# dump jsonservice into urlpatterns:
# (r'^service1/$', 'djangoapp.views.jsonservice'),
class JSONRPCService(JSONRPCServiceBase):
def __call__(self, request, extra=None):
return self.process(request.raw_post_data)
def jsonremote(service):
"""Make JSONRPCService a decorator so that you can write :
from jsonrpc import JSONRPCService
chatservice = JSONRPCService()
@jsonremote(chatservice)
def login(request, user_name):
(...)
"""
def remotify(func):
if isinstance(service, JSONRPCService):
service.add_method(func.__name__, func)
else:
emsg = 'Service "%s" not found' % str(service.__name__)
raise NotImplementedError(emsg)
return func
return remotify
# FormProcessor provides a mechanism for turning Django Forms into JSONRPC
# Services. If you have an existing Django app which makes prevalent
# use of Django Forms it will save you rewriting the app.
# use as follows. in djangoapp/views.py :
#
# class SimpleForm(forms.Form):
# testfield = forms.CharField(max_length=100)
#
# class SimpleForm2(forms.Form):
# testfield = forms.CharField(max_length=20)
#
# processor = FormProcessor({'processsimpleform': SimpleForm,
# 'processsimpleform2': SimpleForm2})
#
# this will result in a JSONRPC service being created with two
# RPC functions. dump "processor" into urlpatterns to make it
# part of the app:
# (r'^formsservice/$', 'djangoapp.views.processor'),
def builderrors(form):
d = {}
for error in form.errors.keys():
if error not in d:
d[error] = []
for errorval in form.errors[error]:
d[error].append(text(errorval))
return d
# contains the list of arguments in each field
field_names = {
'CharField': ['max_length', 'min_length'],
'IntegerField': ['max_value', 'min_value'],
'FloatField': ['max_value', 'min_value'],
'DecimalField': ['max_value', 'min_value', 'max_digits', 'decimal_places'],
'DateField': ['input_formats'],
'DateTimeField': ['input_formats'],
'TimeField': ['input_formats'],
'RegexField': ['max_length', 'min_length'], # sadly we can't get the expr
'EmailField': ['max_length', 'min_length'],
'URLField': ['max_length', 'min_length', 'verify_exists', 'user_agent'],
'ChoiceField': ['choices'],
'FilePathField': ['path', 'match', 'recursive', 'choices'],
'IPAddressField': ['max_length', 'min_length'],
}
def describe_field_errors(field):
res = {}
field_type = field.__class__.__name__
msgs = {}
for n, m in field.error_messages.items():
msgs[n] = text(m)
res['error_messages'] = msgs
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
res['fields'] = map(describe_field, field.fields)
return res
def describe_fields_errors(fields, field_names):
res = {}
if not field_names:
field_names = fields.keys()
for name in field_names:
field = fields[name]
res[name] = describe_field_errors(field)
return res
def describe_field(field):
res = {}
field_type = field.__class__.__name__
for fname in (field_names.get(field_type, []) +
['help_text', 'label', 'initial', 'required']):
res[fname] = getattr(field, fname)
if field_type in ['ComboField', 'MultiValueField', 'SplitDateTimeField']:
res['fields'] = map(describe_field, field.fields)
return res
def describe_fields(fields, field_names):
res = {}
if not field_names:
field_names = fields.keys()
for name in field_names:
field = fields[name]
res[name] = describe_field(field)
return res
class FormProcessor(JSONRPCService):
def __init__(self, forms, _formcls=None):
if _formcls is None:
JSONRPCService.__init__(self)
for k in forms.keys():
s = FormProcessor({}, forms[k])
self.add_method(k, s.__process)
else:
JSONRPCService.__init__(self, forms)
self.formcls = _formcls
def __process(self, request, params, command=None):
f = self.formcls(params)
if command is None: # just validate
if not f.is_valid():
return {'success': False, 'errors': builderrors(f)}
return {'success': True}
elif 'describe_errors' in command:
field_names = command['describe_errors']
return describe_fields_errors(f.fields, field_names)
elif 'describe' in command:
field_names = command['describe']
return describe_fields(f.fields, field_names)
elif 'save' in command:
if not f.is_valid():
return {'success': False, 'errors': builderrors(f)}
instance = f.save() # XXX: if you want more, over-ride save.
return {'success': True, 'instance': json_convert(instance)}
elif 'html' in command:
return {'success': True, 'html': f.as_table()}
return "unrecognised command"
# The following is incredibly convenient for saving vast amounts of
# coding, avoiding doing silly things like this:
# jsonresult = {'field1': djangoobject.field1,
# 'field2': djangoobject.date.strftime('%Y.%M'),
# ..... }
#
# The date/time flatten function is there because JSONRPC doesn't
# support date/time objects or formats, so conversion to a string
# is the most logical choice. pyjamas, being python, can easily
# be used to parse the string result at the other end.
#
# use as follows:
#
# jsonservice = JSONRPCService()
#
# @jsonremote(jsonservice)
# def list_some_model(request, start=0, count=10):
# l = SomeDjangoModelClass.objects.filter()
# res = json_convert(l[start:end])
#
# @jsonremote(jsonservice)
# def list_another_model(request, start=0, count=10):
# l = AnotherDjangoModelClass.objects.filter()
# res = json_convert(l[start:end])
#
# dump jsonservice into urlpatterns to make the two RPC functions,
# list_some_model and list_another_model part of the django app:
# (r'^service1/$', 'djangoapp.views.jsonservice'),
def dict_datetimeflatten(item):
d = {}
for k, v in item.items():
k = str(k)
if isinstance(v, datetime.date):
d[k] = str(v)
elif isinstance(v, dict):
d[k] = dict_datetimeflatten(v)
else:
d[k] = v
return d
def json_convert(l, fields=None):
res = []
for item in serialize('python', l, fields=fields):
res.append(dict_datetimeflatten(item))
return res