Passed
Pull Request — master (#3)
by Yang
04:58
created

Python.orthanc.query   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 140
Duplicated Lines 46.43 %

Importance

Changes 0
Metric Value
eloc 86
dl 65
loc 140
rs 10
c 0
b 0
f 0
wmc 20

5 Methods

Rating   Name   Duplication   Size   Complexity  
A orthanc_query.getOrthanc() 21 21 3
A orthanc_query.postOrthanc() 23 23 3
A orthanc_query.flatUnZip() 0 26 5
A orthanc_query.deleteOrthanc() 21 21 3
B orthanc_query.getPatientZipOrthanc() 0 30 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import requests
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
import logging
0 ignored issues
show
introduced by
standard import "import logging" should be placed before "import requests"
Loading history...
3
import os
0 ignored issues
show
introduced by
standard import "import os" should be placed before "import requests"
Loading history...
4
import shutil
0 ignored issues
show
introduced by
standard import "import shutil" should be placed before "import requests"
Loading history...
5
import zipfile
0 ignored issues
show
introduced by
standard import "import zipfile" should be placed before "import requests"
Loading history...
6
import sys
0 ignored issues
show
introduced by
standard import "import sys" should be placed before "import requests"
Loading history...
7
from dotenv import load_dotenv
8
from PythonUtils.file import is_name_unique
0 ignored issues
show
introduced by
Unable to import 'PythonUtils.file'
Loading history...
9
10
11
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
12
13
class orthanc_query:
0 ignored issues
show
Coding Style Naming introduced by
The name orthanc_query does not conform to the class naming conventions ([A-Z_][a-zA-Z0-9]+$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The variable __class__ seems to be unused.
Loading history...
14
15 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
16
    def getOrthanc(endpoint):
0 ignored issues
show
Coding Style Naming introduced by
The name getOrthanc does not conform to the method naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
17
        """
18
        Get from a Orthanc endpoint
19
        :param endpoint:
20
        :return: bool on if such PSCID (INSTITUTIONID + PROJECTID + SUBJECTID) exist already.
21
        """
22
        logger = logging.getLogger('Orthanc_get')
23
        logger.info("Getting Orthanc endpoint: "+ endpoint + "at")
24
        success = load_dotenv()
25
        if not success:
26
            raise ImportError("Credential .env NOT FOUND! Please ensure .env is set with all the necessary credentials!")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (121/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
27
        url = os.getenv("OrthancURL")
28
        updatedurl = url + endpoint
29
        logger.info(updatedurl)
30
31
        with requests.Session() as s:
0 ignored issues
show
Coding Style Naming introduced by
The name s does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
32
            r = s.get(updatedurl)
0 ignored issues
show
Coding Style Naming introduced by
The name r does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
33
            logger.info("Get Result:" + str(r.status_code) + r.reason)
34
35
            return r.status_code, r.json()
36
37 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
38
    def postOrthanc(endpoint, data):
0 ignored issues
show
Coding Style Naming introduced by
The name postOrthanc does not conform to the method naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
39
        """
40
        Get from a Orthanc endpoint
41
        :param endpoint:
42
        :param data
43
        :return: bool on if such PSCID (INSTITUTIONID + PROJECTID + SUBJECTID) exist already.
44
        """
45
        logger = logging.getLogger('Orthanc_post')
46
        logger.info("Post Orthanc endpoint: "+ endpoint + "at")
47
        success = load_dotenv()
48
        if not success:
49
            raise ImportError("Credential .env NOT FOUND! Please ensure .env is set with all the necessary credentials!")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (121/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
50
        url = os.getenv("OrthancURL")
51
        updatedurl = url + endpoint
52
        logger.info(updatedurl)
53
54
        with requests.Session() as s:
0 ignored issues
show
Coding Style Naming introduced by
The name s does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
55
            r = s.post(updatedurl, files=data)
0 ignored issues
show
Coding Style Naming introduced by
The name r does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
56
57
            logger.info("Post Result:" + str(r.status_code) + r.reason)
58
59
            return r.status_code, r
60
61 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
62
    def deleteOrthanc(endpoint):
0 ignored issues
show
Coding Style Naming introduced by
The name deleteOrthanc does not conform to the method naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
63
        """
64
        Delete from a Orthanc endpoint
65
        :param endpoint:
66
        :return: bool on if such PSCID (INSTITUTIONID + PROJECTID + SUBJECTID) exist already.
67
        """
68
        logger = logging.getLogger('Orthanc_delete')
69
        logger.info("Deleting Orthanc endpoint: "+ endpoint + "at")
70
        success = load_dotenv()
71
        if not success:
72
            raise ImportError("Credential .env NOT FOUND! Please ensure .env is set with all the necessary credentials!")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (121/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
73
        url = os.getenv("OrthancURL")
74
        updatedurl = url + endpoint
75
        logger.info(updatedurl)
76
77
        with requests.Session() as s:
0 ignored issues
show
Coding Style Naming introduced by
The name s does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
78
            r = s.delete(updatedurl)
0 ignored issues
show
Coding Style Naming introduced by
The name r does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
79
            logger.info("Deletion Result:" + str(r.status_code) + r.reason)
80
81
        return r.status_code, r.json()
82
83
    @staticmethod
84
    def getPatientZipOrthanc(endpoint):
0 ignored issues
show
Coding Style Naming introduced by
The name getPatientZipOrthanc does not conform to the method naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
85
        """
86
        Get Orthanc endpoint archive ZIP files.
87
        :param endpoint:
88
        :return: status of the get requests, and the actual local file name saved in the process.
89
        """
90
        logger = logging.getLogger('Orthanc_getzip')
91
        logger.info("Downloading Orthanc endpoint: " + endpoint + " at")
92
        success = load_dotenv()
93
        if not success:
94
            raise ImportError("Credential .env NOT FOUND! Please ensure .env is set with all the necessary credentials!")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (121/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
95
        url = os.getenv("OrthancURL")
96
97
        # endpiont should be something like /studies/SUTDY_UUID/
98
        query = url + "patients/" + endpoint + '/archive'
99
        logger.info(query)
100
101
        with requests.Session() as s:
0 ignored issues
show
Coding Style Naming introduced by
The name s does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
102
            r = s.get(query, stream=True, verify=False)  # auth=(orthanc_user, orthanc_password)
0 ignored issues
show
Coding Style Naming introduced by
The name r does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
103
104
            local_filename = endpoint + ".zip"
105
            # NOTE the stream=True parameter
106
            with open(local_filename, 'wb') as f:
0 ignored issues
show
Coding Style Naming introduced by
The name f does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
107
                for chunk in r.iter_content(chunk_size=1024):
108
                    if chunk:  # filter out keep-alive new chunks
109
                        f.write(chunk)
110
                        # f.flush() commented by recommendation from J.F.Sebastian
111
        logger.info(str(r.status_code) + r.reason)
112
        return r.status_code, local_filename
113
114
    @staticmethod
115
    def flatUnZip(input_zip, out_dir):
0 ignored issues
show
Coding Style Naming introduced by
The name flatUnZip does not conform to the method naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
116
        """
117
        Inpsired by https://stackoverflow.com/questions/4917284/extract-files-from-zip-without-keeping-the-structure-using-python-zipfile
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (137/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
118
        Added function to hanlde non-unique file names which are probably standarderized by Orthanc.
119
        :param input_zip:
120
        :param out_dir:
121
        :return:
122
        """
123
124
        with zipfile.ZipFile(input_zip) as zip_file:
125
            for member in zip_file.namelist():
126
                filename = os.path.basename(member)
127
                # skip directories
128
                if not filename:
129
                    continue
130
131
                # copy file (taken from zipfile's extract)
132
                source = zip_file.open(member)
133
134
                proposed_filename = os.path.join(out_dir, filename)
135
                # handle duplicate names!
136
                _, unique_output_filename = is_name_unique(proposed_filename)
137
                target = open(unique_output_filename, "wb")
138
                with source, target:
139
                    shutil.copyfileobj(source, target)
140