Passed
Pull Request — master (#259)
by Piotr
01:25
created

LazySettings.get()   A

Complexity

Conditions 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 2
1
from django.conf import settings as django_settings
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
from django.test.signals import setting_changed
3
from django.utils import six
4
from django.utils.functional import LazyObject
5
from django.utils.module_loading import import_string
6
7
8
DJOSER_SETTINGS_NAMESPACE = 'DJOSER'
9
10
11
class ObjDict(dict):
0 ignored issues
show
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...
12
    def __getattribute__(self, item):
13
        try:
14
            is_list_of_strings = (
15
                isinstance(self[item], list) and
16
                all(isinstance(elem, str) for elem in self[item])
17
            )
18
19
            if is_list_of_strings:
20
                self[item] = [import_string(func) for func in self[item]]
21
            elif isinstance(self[item], str):
22
                self[item] = import_string(self[item])
23
            value = self[item]
24
        except KeyError:
25
            value = super(ObjDict, self).__getattribute__(item)
26
27
        return value
28
29
30
default_settings = {
0 ignored issues
show
Coding Style Naming introduced by
The name default_settings does not conform to the constant naming conventions ((([A-Z_][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...
31
    'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False,
32
    'PASSWORD_VALIDATORS': [],
33
    'TOKEN_MODEL': None,
34
    'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy',
35
    'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [],
36
    'VIEW_PIPELINE_ADAPTER':
37
        'djoser.pipelines.base.default_view_pipeline_adapter',
38
39
    'PIPELINES': ObjDict({
40
        'user_activate': [
41
            'djoser.pipelines.user_activate.serialize_request',
42
            'djoser.pipelines.user_activate.perform',
43
            'djoser.pipelines.user_activate.signal',
44
            'djoser.pipelines.email.confirmation_email',
45
        ],
46
        'user_create': [
47
            'djoser.pipelines.user_create.serialize_request',
48
            'djoser.pipelines.user_create.perform',
49
            'djoser.pipelines.user_create.serialize_instance',
50
            'djoser.pipelines.user_create.signal',
51
            'djoser.pipelines.email.confirmation_email',
52
        ],
53
        'user_detail': [
54
            'djoser.pipelines.user_detail.perform',
55
            'djoser.pipelines.user_detail.serialize_instance',
56
        ],
57
        'user_update': [
58
            'djoser.pipelines.user_update.serialize_request',
59
            'djoser.pipelines.user_update.perform',
60
            'djoser.pipelines.user_update.signal',
61
            'djoser.pipelines.user_update.serialize_instance',
62
        ],
63
        'user_delete': [
64
            'djoser.pipelines.user_delete.serialize_request',
65
            'djoser.pipelines.user_delete.perform',
66
            'djoser.pipelines.user_delete.signal',
67
        ],
68
        'username_update': [
69
            'djoser.pipelines.username_update.serialize_request',
70
            'djoser.pipelines.username_update.perform',
71
            'djoser.pipelines.username_update.signal',
72
        ],
73
        'password_update': [
74
            'djoser.pipelines.password_update.serialize_request',
75
            'djoser.pipelines.password_update.perform',
76
            'djoser.pipelines.password_update.signal',
77
        ],
78
        'password_reset': [
79
            'djoser.pipelines.password_reset.serialize_request',
80
            'djoser.pipelines.password_reset.perform',
81
        ],
82
        'password_reset_confirm': [
83
            'djoser.pipelines.password_reset_confirm.serialize_request',
84
            'djoser.pipelines.password_reset_confirm.perform',
85
            'djoser.pipelines.password_reset_confirm.signal',
86
        ],
87
        'token_create': [
88
            'djoser.pipelines.token_create.serialize_request',
89
            'djoser.pipelines.token_create.perform',
90
            'djoser.pipelines.token_create.signal',
91
        ],
92
        'token_destroy': [
93
            'djoser.pipelines.token_destroy.perform',
94
            'djoser.pipelines.token_destroy.signal',
95
        ]
96
    }),
97
    'SERIALIZERS': ObjDict({
98
        'user_activate':
99
            'djoser.serializers.UserActivateSerializer',
100
        'user_create':
101
            'djoser.serializers.UserCreateSerializer',
102
        'user':
103
            'djoser.serializers.UserSerializer',
104
        'user_delete':
105
            'djoser.serializers.UserDeleteSerializer',
106
        'username_update':
107
            'djoser.serializers.UsernameUpdateSerializer',
108
        'password_update':
109
            'djoser.serializers.PasswordUpdateSerializer',
110
        'password_reset':
111
            'djoser.serializers.PasswordResetSerializer',
112
        'password_reset_confirm':
113
            'djoser.serializers.PasswordResetConfirmSerializer',
114
        'token':
115
            'djoser.serializers.TokenSerializer',
116
        'token_create':
117
            'djoser.serializers.TokenCreateSerializer',
118
    }),
119
    'EMAIL': ObjDict({
120
        'activation': 'djoser.email.ActivationEmail',
121
        'confirmation': 'djoser.email.ConfirmationEmail',
122
        'password_reset': 'djoser.email.PasswordResetEmail',
123
    }),
124
}
125
126
SETTINGS_TO_IMPORT = [
127
    'TOKEN_MODEL', 'SOCIAL_AUTH_TOKEN_STRATEGY', 'VIEW_PIPELINE_ADAPTER'
128
]
129
130
131
class Settings(object):
0 ignored issues
show
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...
132
    def __init__(self, default_settings, explicit_overriden_settings=None):
0 ignored issues
show
Comprehensibility Bug introduced by
default_settings is re-defining a name which is already available in the outer-scope (previously defined on line 30).

It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior:

param = 5

class Foo:
    def __init__(self, param):   # "param" would be flagged here
        self.param = param
Loading history...
Unused Code introduced by
The argument default_settings seems to be unused.
Loading history...
133
        if explicit_overriden_settings is None:
134
            explicit_overriden_settings = {}
135
136
        overriden_settings = getattr(
137
            django_settings, DJOSER_SETTINGS_NAMESPACE, {}
138
        ) or explicit_overriden_settings
139
140
        self._load_default_settings()
141
        self._override_settings(overriden_settings)
142
        self._init_settings_to_import()
143
144
    def _load_default_settings(self):
145
        for setting_name, setting_value in six.iteritems(default_settings):
146
            if setting_name.isupper():
147
                setattr(self, setting_name, setting_value)
148
149
    def _override_settings(self, overriden_settings):
150
        for setting_name, setting_value in six.iteritems(overriden_settings):
151
            value = setting_value
152
            if isinstance(setting_value, dict):
153
                value = getattr(self, setting_name, {})
154
                value.update(ObjDict(setting_value))
155
            setattr(self, setting_name, value)
156
157
    def _init_settings_to_import(self):
158
        for setting_name in SETTINGS_TO_IMPORT:
159
            value = getattr(self, setting_name)
160
            if isinstance(value, str):
161
                setattr(self, setting_name, import_string(value))
162
163
164
class LazySettings(LazyObject):
0 ignored issues
show
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...
165
    def _setup(self, explicit_overriden_settings=None):
0 ignored issues
show
Bug introduced by
Parameters differ from overridden '_setup' method
Loading history...
166
        self._wrapped = Settings(default_settings, explicit_overriden_settings)
167
168
169
settings = LazySettings()
0 ignored issues
show
Coding Style Naming introduced by
The name settings does not conform to the constant naming conventions ((([A-Z_][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...
170
171
172
def reload_djoser_settings(*args, **kwargs):
0 ignored issues
show
Coding Style introduced by
This function 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 argument args seems to be unused.
Loading history...
173
    global settings
0 ignored issues
show
Coding Style introduced by
Usage of the global statement should be avoided.

Usage of global can make code hard to read and test, its usage is generally not recommended unless you are dealing with legacy code.

Loading history...
Coding Style Naming introduced by
The name settings does not conform to the constant naming conventions ((([A-Z_][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...
174
    setting, value = kwargs['setting'], kwargs['value']
175
    if setting == DJOSER_SETTINGS_NAMESPACE:
176
        settings._setup(explicit_overriden_settings=value)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like _setup was declared protected and should not be accessed from this context.

Prefixing a member variable _ is usually regarded as the equivalent of declaring it with protected visibility that exists in other languages. Consequentially, such a member should only be accessed from the same class or a child class:

class MyParent:
    def __init__(self):
        self._x = 1;
        self.y = 2;

class MyChild(MyParent):
    def some_method(self):
        return self._x    # Ok, since accessed from a child class

class AnotherClass:
    def some_method(self, instance_of_my_child):
        return instance_of_my_child._x   # Would be flagged as AnotherClass is not
                                         # a child class of MyParent
Loading history...
177
178
179
setting_changed.connect(reload_djoser_settings)
180