Explorar o código

CI changes:
- added pylintrc file
- added a Makefile and updated gitlab-ci script commands
- improved pylint score of the pycs/database module

Dimitri Korsch %!s(int64=3) %!d(string=hai) anos
pai
achega
0c8332a22d

+ 4 - 11
.gitlab-ci.yml

@@ -33,18 +33,11 @@ webui:
     - python -V
     - python -m venv env
     - source env/bin/activate
-    - pip install numpy opencv-python Pillow scipy
-    - pip install eventlet flask python-socketio
-    - pip install coverage pylint
+    - pip install -r requirements.txt
+    - pip install -r requirements.dev.txt
   script:
-    - coverage run --source=pycs/ -m unittest discover test/
-    - "pylint --fail-under=9.5
-         --disable=duplicate-code
-         --disable=missing-module-docstring
-         --disable=too-many-instance-attributes
-         --extension-pkg-whitelist=cv2
-         --module-rgx='^[A-Za-z0-9]+$' --class-rgx='^[A-Za-z0-9]+$'
-         app.py pycs"
+    - make run_coverage
+    - make run_pylint
 
 tests_3.6:
   stage: test

+ 627 - 0
.pylintrc

@@ -0,0 +1,627 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-allow-list=
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
+# for backward compatibility.)
+extension-pkg-whitelist=cv2
+
+# Return non-zero exit code if any of these messages/categories are detected,
+# even if score is above --fail-under value. Syntax same as enable. Messages
+# specified are enabled, while categories only check already-enabled messages.
+fail-on=
+
+# Specify a score threshold to be exceeded before program exits with error.
+fail-under=9.5
+
+# Files or directories to be skipped. They should be base names, not paths.
+ignore=CVS
+
+# Add files or directories matching the regex patterns to the ignore-list. The
+# regex matches against paths.
+ignore-paths=
+
+# Files or directories matching the regex patterns are skipped. The regex
+# matches against base names, not paths.
+ignore-patterns=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python module names) to load,
+# usually to register additional checkers.
+load-plugins=pylint_flask, pylint_flask_sqlalchemy
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=print-statement,
+        parameter-unpacking,
+        unpacking-in-except,
+        old-raise-syntax,
+        backtick,
+        long-suffix,
+        old-ne-operator,
+        old-octal-literal,
+        import-star-module-level,
+        non-ascii-bytes-literal,
+        raw-checker-failed,
+        bad-inline-option,
+        locally-disabled,
+        file-ignored,
+        suppressed-message,
+        useless-suppression,
+        deprecated-pragma,
+        use-symbolic-message-instead,
+        apply-builtin,
+        basestring-builtin,
+        buffer-builtin,
+        cmp-builtin,
+        coerce-builtin,
+        execfile-builtin,
+        file-builtin,
+        long-builtin,
+        raw_input-builtin,
+        reduce-builtin,
+        standarderror-builtin,
+        unicode-builtin,
+        xrange-builtin,
+        coerce-method,
+        delslice-method,
+        getslice-method,
+        setslice-method,
+        no-absolute-import,
+        old-division,
+        dict-iter-method,
+        dict-view-method,
+        next-method-called,
+        metaclass-assignment,
+        indexing-exception,
+        raising-string,
+        reload-builtin,
+        oct-method,
+        hex-method,
+        nonzero-method,
+        cmp-method,
+        input-builtin,
+        round-builtin,
+        intern-builtin,
+        unichr-builtin,
+        map-builtin-not-iterating,
+        zip-builtin-not-iterating,
+        range-builtin-not-iterating,
+        filter-builtin-not-iterating,
+        using-cmp-argument,
+        eq-without-hash,
+        div-method,
+        idiv-method,
+        rdiv-method,
+        exception-message-attribute,
+        invalid-str-codec,
+        sys-max-int,
+        bad-python3-import,
+        deprecated-string-function,
+        deprecated-str-translate-call,
+        deprecated-itertools-function,
+        deprecated-types-field,
+        next-method-defined,
+        dict-items-not-iterating,
+        dict-keys-not-iterating,
+        dict-values-not-iterating,
+        deprecated-operator-function,
+        deprecated-urllib-function,
+        xreadlines-attribute,
+        deprecated-sys-function,
+        exception-escape,
+        comprehension-escape,
+        duplicate-code,
+        missing-module-docstring,
+        too-many-instance-attributes
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a score less than or equal to 10. You
+# have access to the variables 'error', 'warning', 'refactor', and 'convention'
+# which contain the number of messages in each category, as well as 'statement'
+# which is the total number of statements analyzed. This score is used by the
+# global evaluation report (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit,argparse.parse_error
+
+
+[LOGGING]
+
+# The type of string formatting that logging methods do. `old` means using %
+# formatting, `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of names allowed to shadow builtins
+allowed-redefined-builtins=
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+          _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+          bar,
+          baz,
+          toto,
+          tutu,
+          tata
+
+# Bad variable names regexes, separated by a comma. If names match any regex,
+# they will always be refused
+bad-names-rgxs=
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class constant names.
+class-const-naming-style=UPPER_CASE
+
+# Regular expression matching correct class constant names. Overrides class-
+# const-naming-style.
+#class-const-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+class-rgx=^[A-Za-z0-9]+$
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+           j,
+           k,
+           ex,
+           id,
+           Run,
+           _
+
+# Good variable names regexes, separated by a comma. If names match any regex,
+# they will always be accepted
+good-names-rgxs=
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+module-rgx=^[A-Za-z0-9]+$
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[STRING]
+
+# This flag controls whether inconsistent-quotes generates a warning when the
+# character used as a quote delimiter is used inconsistently within a module.
+check-quote-consistency=no
+
+# This flag controls whether the implicit-str-concat should generate a warning
+# on implicit string concatenation in sequences defined over several lines.
+check-str-concat-over-line-jumps=no
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )?<?https?://\S+>?$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
+# tab).
+indent-string='    '
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Ignore function signatures when computing similarities.
+ignore-signatures=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local,scoped_session
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis). It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+# List of decorators that change the signature of a decorated function.
+signature-mutators=
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+      XXX,
+      TODO
+
+# Regular expression of note tags to take in consideration.
+#notes-rgx=
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it work,
+# install the 'python-enchant' package.
+spelling-dict=
+
+# List of comma separated words that should be considered directives if they
+# appear and the beginning of a comment and should not be checked.
+spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains the private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to the private dictionary (see the
+# --spelling-private-dict-file option) instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement (see R0916).
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[IMPORTS]
+
+# List of modules that can be imported at any level, not just the top level
+# one.
+allow-any-import-level=
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=
+
+# Output a graph (.gv or any supported image format) of external dependencies
+# to the given file (report RP0402 must not be disabled).
+ext-import-graph=
+
+# Output a graph (.gv or any supported image format) of all (i.e. internal and
+# external) dependencies to the given file (report RP0402 must not be
+# disabled).
+import-graph=
+
+# Output a graph (.gv or any supported image format) of internal dependencies
+# to the given file (report RP0402 must not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+# Couples of modules and preferred modules, separated by a comma.
+preferred-modules=
+
+
+[CLASSES]
+
+# Warn about protected attribute access inside special methods
+check-protected-access-in-special-methods=no
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+                      __new__,
+                      setUp,
+                      __post_init__
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+                  _fields,
+                  _replace,
+                  _source,
+                  _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+                       Exception

+ 1 - 7
Makefile

@@ -16,10 +16,4 @@ run_coverage:
 	coverage report -m
 
 run_pylint:
-	pylint --fail-under=9.5 \
-         --disable=duplicate-code \
-         --disable=missing-module-docstring \
-         --disable=too-many-instance-attributes \
-         --extension-pkg-whitelist=cv2 \
-         --module-rgx='^[A-Za-z0-9]+$' --class-rgx='^[A-Za-z0-9]+$' \
-         app.py pycs
+	pylint --rcfile=.pylintrc app.py pycs

+ 5 - 3
pycs/__init__.py

@@ -24,15 +24,17 @@ app = Flask(__name__)
 
 if "unittest" in sys.modules:
     # creates an in-memory DB
-    db_file = ""
+    DB_FILE = ""
 else:
-    db_file = Path.cwd() / settings.database
+    DB_FILE = Path.cwd() / settings.database
 
-app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_file}"
+app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{DB_FILE}"
 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
 
+# pylint: disable=unused-argument
 @event.listens_for(Engine, "connect")
 def set_sqlite_pragma(dbapi_connection, connection_record):
+    """ enables foreign keys on every established connection """
     cursor = dbapi_connection.cursor()
     cursor.execute("PRAGMA foreign_keys=ON")
     cursor.close()

+ 3 - 1
pycs/database/Collection.py

@@ -1,12 +1,12 @@
 from __future__ import annotations
 
-from contextlib import closing
 from typing import List
 
 from pycs import db
 from pycs.database.base import NamedBaseModel
 
 class Collection(NamedBaseModel):
+    """ DB Model for collections """
 
     # table columns
     project_id = db.Column(
@@ -52,6 +52,8 @@ class Collection(NamedBaseModel):
         :param limit: file limit
         :return: iterator of files
         """
+
+        # pylint: disable=import-outside-toplevel
         from pycs.database.File import File
         return self.files.order_by(File.id).offset(offset).limit(limit)
 

+ 35 - 7
pycs/database/File.py

@@ -10,14 +10,13 @@ from pathlib import Path
 from pycs import db
 from pycs.database.Collection import Collection
 from pycs.database.Result import Result
+from pycs.database.Label import Label
 from pycs.database.base import NamedBaseModel
 from pycs.database.util import commit_on_return
 
 
 class File(NamedBaseModel):
-    """
-    database class for files
-    """
+    """ DB Model for files """
 
     # table columns
     uuid = db.Column(db.String, nullable=False)
@@ -71,10 +70,12 @@ class File(NamedBaseModel):
 
     @property
     def filename(self):
+        """ filename consisting of a name and an extension """
         return f"{self.name}{self.extension}"
 
     @property
     def absolute_path(self) -> str:
+        """ returns an absolute of the file """
         path = Path(self.path)
 
         if path.is_absolute():
@@ -82,10 +83,19 @@ class File(NamedBaseModel):
 
         return str(Path.cwd() / path)
 
+    # pylint: disable=arguments-differ
     def delete(self, commit: bool = True):
+        """
+            after the object is deleted, the according physical file
+            is also delete if commit was True
+        """
+
+        # pylint: disable=unexpected-keyword-arg
         super().delete(commit=commit)
-        # remove file from folder
-        os.remove(self.path)
+
+        if commit:
+            os.remove(self.path)
+
         # TODO: remove temp files
         warnings.warn("Temporary files may still exist!")
 
@@ -140,6 +150,7 @@ class File(NamedBaseModel):
         :return: another file or None
         """
 
+        # pylint: disable=no-member
         return self._get_another_file(File.id < self.id)\
             .order_by(File.id.desc()).first()
 
@@ -161,13 +172,20 @@ class File(NamedBaseModel):
 
         :return: another file or None
         """
+
+        # pylint: disable=no-member
         return self._get_another_file(
             File.id < self.id, File.collection_id == self.collection_id)\
             .order_by(File.id.desc()).first()
 
 
-    def result(self, id: int) -> T.Optional[Result]:
-        return self.results.get(id)
+    def result(self, identifier: int) -> T.Optional[Result]:
+        """
+        get one of the file's results
+
+        :return: result object or None
+        """
+        return self.results.get(identifier)
 
 
     @commit_on_return
@@ -176,6 +194,11 @@ class File(NamedBaseModel):
                       result_type: str,
                       label: T.Optional[T.Union[Label, int]] = None,
                       data: T.Optional[dict] = None) -> Result:
+        """
+        Creates a result and returns the created object
+
+        :return: result object
+        """
 
         result = Result.new(commit=False,
                             file_id=self.id,
@@ -196,6 +219,11 @@ class File(NamedBaseModel):
 
 
     def remove_results(self, origin='pipeline') -> T.List[Result]:
+        """
+        Remove assigned results, but return them.
+
+        :return: list of result objects
+        """
 
         results = Result.query.filter(
             Result.file_id == self.id,

+ 8 - 4
pycs/database/Label.py

@@ -1,12 +1,14 @@
 from __future__ import annotations
 
+import typing as T
+
 from datetime import datetime
 
 from pycs import db
 from pycs.database.base import NamedBaseModel
 from pycs.database.util import commit_on_return
 
-def compare_children(start_label: Label, id: int) -> bool:
+def compare_children(start_label: Label, identifier: int) -> bool:
     """ check for cyclic relationships """
 
     labels_to_check = [start_label]
@@ -14,19 +16,21 @@ def compare_children(start_label: Label, id: int) -> bool:
     while labels_to_check:
         label = labels_to_check.pop(0)
 
-        if label.id == id:
+        if label.id == identifier:
             return False
 
         labels_to_check.extend(label.children)
 
     return True
 
-def _Label_id():
+def _label_id():
     return Label.id
 
 class Label(NamedBaseModel):
+    """ DB Model for labels """
 
     id = db.Column(db.Integer, primary_key=True)
+
     project_id = db.Column(
         db.Integer,
         db.ForeignKey("project.id", ondelete="CASCADE"),
@@ -49,7 +53,7 @@ class Label(NamedBaseModel):
     # relationships to other models
     parent = db.relationship("Label",
         backref="children",
-        remote_side=_Label_id)
+        remote_side=_label_id)
 
     results = db.relationship("Result",
         backref="label",

+ 11 - 5
pycs/database/LabelProvider.py

@@ -10,7 +10,7 @@ from pycs.interfaces.LabelProvider import LabelProvider as LabelProviderInterfac
 
 class LabelProvider(NamedBaseModel):
     """
-    database class for label providers
+    DB model for label providers
     """
 
     description = db.Column(db.String)
@@ -33,10 +33,14 @@ class LabelProvider(NamedBaseModel):
 
     @classmethod
     def discover(cls, root: Path):
+        """
+            searches for label providers under the given path
+            and stores them in the database
+        """
 
         for folder, conf_path in _find_files(root):
-            with open(conf_path) as f:
-                config = json.load(f)
+            with open(conf_path) as conf_file:
+                config = json.load(conf_file)
 
             provider, _ = cls.get_or_create(
                 root_folder=str(folder),
@@ -53,11 +57,13 @@ class LabelProvider(NamedBaseModel):
 
     @property
     def root(self) -> Path:
+        """ returns the root folder as Path object """
         return Path(self.root_folder)
 
 
     @property
     def configuration_file_path(self) -> str:
+        """ return the configuration file as Path object """
         return str(self.root / self.configuration_file)
 
 
@@ -84,7 +90,8 @@ class LabelProvider(NamedBaseModel):
 
 
 def _find_files(root: str, config_regex=re.compile(r'^configuration(\d+)?\.json$')):
-    # list folders in labels/
+    """ generator for config files found under the given path """
+
     for folder in Path(root).glob('*'):
         # list files
         for file_path in folder.iterdir():
@@ -98,4 +105,3 @@ def _find_files(root: str, config_regex=re.compile(r'^configuration(\d+)?\.json$
 
             # yield element
             yield folder, file_path
-

+ 16 - 7
pycs/database/Model.py

@@ -8,7 +8,7 @@ from pycs.database.util import commit_on_return
 
 class Model(NamedBaseModel):
     """
-    database class for ML Models
+    DB model for ML models
     """
 
     description = db.Column(db.String)
@@ -31,18 +31,20 @@ class Model(NamedBaseModel):
 
     @classmethod
     def discover(cls, root: Path, config_name: str = "configuration.json"):
+        """
+            searches for models under the given path
+            and stores them in the database
+        """
         for folder in Path(root).glob("*"):
-            with open(folder / config_name) as f:
-                config = json.load(f)
+            with open(folder / config_name) as config_file:
+                config = json.load(config_file)
 
             # extract data
             name = config['name']
             description = config.get('description', None)
             supports = config['supports']
 
-            model, is_new = cls.get_or_create(root_folder=str(folder))
-
-            assert model is not None
+            model, _ = cls.get_or_create(root_folder=str(folder))
 
             model.name = name
             model.description = description
@@ -52,11 +54,17 @@ class Model(NamedBaseModel):
         db.session.commit()
 
     @property
-    def supports(self):
+    def supports(self) -> dict:
+        """ getter for the 'supports' attribute """
         return json.loads(self.supports_encoded)
 
     @supports.setter
     def supports(self, value):
+        """
+            setter for the 'supports' attribute.
+            The attribute is encoded property before assigned to the object.
+        """
+
         if isinstance(value, str):
             self.supports_encoded = value
 
@@ -68,6 +76,7 @@ class Model(NamedBaseModel):
 
     @commit_on_return
     def copy_to(self, name: str, root_folder: str):
+        """ copies current model to another folder and updates the name """
 
         model, is_new = Model.get_or_create(root_folder=root_folder)
 

+ 16 - 3
pycs/database/Project.py

@@ -15,6 +15,8 @@ from pycs.database.util import commit_on_return
 
 
 class Project(NamedBaseModel):
+    """ DB Model for projects """
+
     description = db.Column(db.String)
 
     created = db.Column(db.DateTime, default=datetime.utcnow,
@@ -66,10 +68,12 @@ class Project(NamedBaseModel):
 
     @commit_on_return
     def delete(self) -> T.Tuple[dict, dict]:
+        # pylint: disable=unexpected-keyword-arg
         dump = super().delete(commit=False)
 
         model_dump = {}
         if self.model_id is not None:
+            # pylint: disable=unexpected-keyword-arg
             model_dump = self.model.delete(commit=False)
 
         if os.path.exists(self.root_folder):
@@ -79,7 +83,6 @@ class Project(NamedBaseModel):
         return dump, model_dump
 
 
-
     def label(self, identifier: int) -> T.Optional[Label]:
         """
         get a label using its unique identifier
@@ -117,7 +120,8 @@ class Project(NamedBaseModel):
         :return: list of labels
         """
         warnings.warn("Check performance of this method!")
-        return self.labels.filter(Label.parent_id == None).all()
+        # pylint: disable=no-member
+        return self.labels.filter(Label.parent_id.is_(None)).all()
 
 
     def label_tree_original(self):
@@ -127,6 +131,9 @@ class Project(NamedBaseModel):
         :return: list of labels
         """
         raise NotImplementedError
+        # pylint: disable=unreachable
+        # pylint: disable=pointless-string-statement
+        """
         with closing(self.database.con.cursor()) as cursor:
             cursor.execute('''
                 WITH RECURSIVE
@@ -153,6 +160,7 @@ class Project(NamedBaseModel):
                     lookup[label.parent_id].children.append(label)
 
             return result
+        """
 
 
     def collection(self, identifier: int) -> T.Optional[Collection]:
@@ -205,6 +213,7 @@ class Project(NamedBaseModel):
         return label, is_new
 
 
+    # pylint: disable=too-many-arguments
     @commit_on_return
     def create_collection(self,
                           reference: str,
@@ -236,6 +245,7 @@ class Project(NamedBaseModel):
         return collection, is_new
 
 
+    # pylint: disable=too-many-arguments
     @commit_on_return
     def add_file(self,
                  uuid: str,
@@ -264,6 +274,7 @@ class Project(NamedBaseModel):
         file, is_new = File.get_or_create(
             project_id=self.id, path=path)
 
+        file.uuid = uuid
         file.type = file_type
         file.name = name
         file.extension = extension
@@ -291,6 +302,7 @@ class Project(NamedBaseModel):
 
         :return: a query object
         """
+        # pylint: disable=no-member
         return self.files.filter(~File.results.any())
 
 
@@ -319,7 +331,8 @@ class Project(NamedBaseModel):
 
         :return: a query object
         """
-        return self.get_files(offset, limit).filter(File.collection_id == None)
+        # pylint: disable=no-member
+        return self.get_files(offset, limit).filter(File.collection_id.is_(None))
 
     def files_without_collection(self, offset: int = 0, limit: int = -1) -> T.List[File]:
         """

+ 9 - 5
pycs/database/Result.py

@@ -1,13 +1,12 @@
+import json
 import typing as T
 
-from contextlib import closing
-from json import dumps, loads
-
 from pycs import db
 from pycs.database.base import BaseModel
 from pycs.database.util import commit_on_return
 
 class Result(BaseModel):
+    """ DB Model for projects """
 
     file_id = db.Column(
         db.Integer,
@@ -33,16 +32,22 @@ class Result(BaseModel):
     )
 
     def serialize(self):
+        """ extends the default serialize with the decoded data attribute """
         result = super().serialize()
         result["data"] = self.data
         return result
 
     @property
-    def data(self):
+    def data(self) -> T.Optional[dict]:
+        """ getter for the decoded data attribute """
         return None if self.data_encoded is None else json.loads(self.data_encoded)
 
     @data.setter
     def data(self, value):
+        """
+            setter for the decoded data attribute
+            The attribute is encoded property before assigned to the object.
+        """
         if isinstance(value, str) or value is None:
             self.data_encoded = value
 
@@ -72,4 +77,3 @@ class Result(BaseModel):
         :return:
         """
         self.label_id = label
-

+ 13 - 4
pycs/database/base.py

@@ -1,16 +1,15 @@
 from __future__ import annotations
 
-import datetime
 import typing as T
 
 from flask import abort
 from sqlalchemy_serializer import SerializerMixin
 
-from pycs import app
 from pycs import db
 from pycs.database.util import commit_on_return
 
 class BaseModel(db.Model, SerializerMixin):
+    """ Base model class """
     __abstract__ = True
 
     # setup of the SerializerMixin
@@ -30,6 +29,7 @@ class BaseModel(db.Model, SerializerMixin):
 
 
     def serialize(self) -> dict:
+        """ default model serialize method. adds identifier as alias for id """
         res = self.to_dict()
         res["identifier"] = self.id
         return res
@@ -54,6 +54,7 @@ class BaseModel(db.Model, SerializerMixin):
 
     @classmethod
     def new(cls, commit: bool = True, **kwargs):
+        """ creates a new object. optionally commits the created object. """
         obj = cls(**kwargs)
         db.session.add(obj)
 
@@ -64,6 +65,7 @@ class BaseModel(db.Model, SerializerMixin):
 
     @classmethod
     def get_or_create(cls, **kwargs) -> T.Tuple[BaseModel, bool]:
+        """ get an object from the DB based on the kwargs, or create an object with these. """
 
         is_new = False
 
@@ -78,6 +80,7 @@ class BaseModel(db.Model, SerializerMixin):
 
     @classmethod
     def get_or_404(cls, obj_id: int) -> BaseModel:
+        """ get an object for the given id or raise 404 error if the object is not present """
         obj = cls.query.get(obj_id)
 
         if obj is None:
@@ -86,14 +89,19 @@ class BaseModel(db.Model, SerializerMixin):
         return obj
 
 
-    def commit(self):
+    @staticmethod
+    def commit():
+        """ commit current session """
         db.session.commit()
 
-    def flush(self):
+    @staticmethod
+    def flush():
+        """ flush current session """
         db.session.flush()
 
 
 class NamedBaseModel(BaseModel):
+    """ Extends the base model with a name attribute. """
     __abstract__ = True
 
     name = db.Column(db.String, nullable=False)
@@ -102,4 +110,5 @@ class NamedBaseModel(BaseModel):
 
     @commit_on_return
     def set_name(self, name: str):
+        """ set the name attribute """
         self.name = name

+ 1 - 2
pycs/database/util/JSONEncoder.py

@@ -13,5 +13,4 @@ class JSONEncoder(Base):
         if isinstance(o, BaseModel):
             return o.serialize()
 
-        else:
-            return o.__dict__.copy()
+        return o.__dict__.copy()

+ 1 - 0
pycs/database/util/TreeNodeLabel.py

@@ -2,6 +2,7 @@ from pycs.database.Label import Label
 
 
 class TreeNodeLabel(Label):
+    """ Extends the TreeNodeLabel class with a children attribute """
     def __init__(self, database, row):
         super().__init__(database, row)
         self.children = []

+ 11 - 8
pycs/database/util/__init__.py

@@ -3,16 +3,19 @@ from functools import wraps
 from pycs import db
 
 def commit_on_return(method):
+    """
+        Decorator for model's methods. It provides an extra argument to the method: commit.
+        On return if commit is True, then the database session is commited.
+    """
 
-	@wraps(method)
-	def inner(self, *args, commit: bool = True, **kwargs):
+    @wraps(method)
+    def inner(self, *args, commit: bool = True, **kwargs):
 
-		res = method(self, *args, **kwargs)
+        res = method(self, *args, **kwargs)
 
-		if commit:
-			db.session.commit()
+        if commit:
+            db.session.commit()
 
-		return res
-
-	return inner
+        return res
 
+    return inner

+ 2 - 0
requirements.dev.txt

@@ -1,2 +1,4 @@
 coverage
 pylint
+pylint-flask-sqlalchemy
+pylint-flask

+ 1 - 1
requirements.txt

@@ -7,7 +7,7 @@ flask
 flask-socketio
 flask-sqlalchemy
 flask-migrate
-# python-socketio
+python-socketio
 munch
 scikit-image