Passed
Pull Request — master (#259)
by Piotr
03:28
created

ObjDict.__getattribute__()   B

Complexity

Conditions 6

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
c 2
b 0
f 0
dl 0
loc 16
rs 8
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...
introduced by
Unable to import 'django.conf'
Loading history...
2
from django.test.signals import setting_changed
0 ignored issues
show
introduced by
Unable to import 'django.test.signals'
Loading history...
3
from django.utils import six
0 ignored issues
show
introduced by
Unable to import 'django.utils'
Loading history...
4
from django.utils.functional import LazyObject
0 ignored issues
show
introduced by
Unable to import 'django.utils.functional'
Loading history...
5
from django.utils.module_loading import import_string
0 ignored issues
show
introduced by
Unable to import 'django.utils.module_loading'
Loading history...
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_UPDATE_REQUIRE_RETYPE': False,
32
    'USERNAME_UPDATE_REQUIRE_RETYPE': False,
33
    'PASSWORD_RESET_CONFIRM_REQUIRE_RETYPE': False,
34
    'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False,
35
    'PASSWORD_VALIDATORS': [],
36
    'LOGOUT_ON_PASSWORD_CHANGE': False,
37
    'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy',
38
    'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [],
39
    'TOKEN_MODEL': None,
40
    'VIEW_PIPELINE_ADAPTER':
41
        'djoser.pipelines.base.default_view_pipeline_adapter',
42
43
    'PIPELINES': ObjDict({
44
        'user_activate': [
45
            'djoser.pipelines.user_activate.serialize_request',
46
            'djoser.pipelines.user_activate.perform',
47
            'djoser.pipelines.user_activate.signal',
48
            'djoser.pipelines.email.confirmation_email',
49
        ],
50
        'user_create': [
51
            'djoser.pipelines.user_create.serialize_request',
52
            'djoser.pipelines.user_create.perform',
53
            'djoser.pipelines.user_create.serialize_instance',
54
            'djoser.pipelines.user_create.signal',
55
            'djoser.pipelines.email.activation_email',
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
        'user_detail': [
69
            'djoser.pipelines.user_detail.perform',
70
            'djoser.pipelines.user_detail.serialize_instance',
71
        ],
72
        'username_update': [
73
            'djoser.pipelines.username_update.serialize_request',
74
            'djoser.pipelines.username_update.perform',
75
            'djoser.pipelines.username_update.signal',
76
        ],
77
        'password_update': [
78
            'djoser.pipelines.password_update.serialize_request',
79
            'djoser.pipelines.password_update.perform',
80
            'djoser.pipelines.password_update.signal',
81
        ],
82
        'password_reset': [
83
            'djoser.pipelines.password_reset.serialize_request',
84
            'djoser.pipelines.password_reset.perform',
85
        ],
86
        'password_reset_confirm': [
87
            'djoser.pipelines.password_reset_confirm.serialize_request',
88
            'djoser.pipelines.password_reset_confirm.perform',
89
            'djoser.pipelines.password_reset_confirm.signal',
90
        ],
91
        'token_create': [
92
            'djoser.pipelines.token_create.serialize_request',
93
            'djoser.pipelines.token_create.perform',
94
            'djoser.pipelines.token_create.signal',
95
        ],
96
        'token_destroy': [
97
            'djoser.pipelines.token_destroy.perform',
98
            'djoser.pipelines.token_destroy.signal',
99
        ]
100
    }),
101
    'SERIALIZERS': ObjDict({
102
        'user_activate':
103
            'djoser.serializers.UserActivateSerializer',
104
        'password_reset':
105
            'djoser.serializers.PasswordResetSerializer',
106
        'password_reset_confirm':
107
            'djoser.serializers.PasswordResetConfirmSerializer',
108
        'password_reset_confirm_retype':
109
            'djoser.serializers.PasswordResetConfirmRetypeSerializer',
110
        'set_password':
111
            'djoser.serializers.SetPasswordSerializer',
112
        'set_password_retype':
113
            'djoser.serializers.SetPasswordRetypeSerializer',
114
        'set_username':
115
            'djoser.serializers.SetUsernameSerializer',
116
        'set_username_retype':
117
            'djoser.serializers.SetUsernameRetypeSerializer',
118
        'user_create':
119
            'djoser.serializers.UserCreateSerializer',
120
        'user_delete':
121
            'djoser.serializers.UserDeleteSerializer',
122
        'user':
123
            'djoser.serializers.UserSerializer',
124
        'token':
125
            'djoser.serializers.TokenSerializer',
126
        'token_create':
127
            'djoser.serializers.TokenCreateSerializer',
128
    }),
129
    'EMAIL': ObjDict({
130
        'activation': 'djoser.email.ActivationEmail',
131
        'confirmation': 'djoser.email.ConfirmationEmail',
132
        'password_reset': 'djoser.email.PasswordResetEmail',
133
    }),
134
}
135
136
SETTINGS_TO_IMPORT = [
137
    'TOKEN_MODEL', 'SOCIAL_AUTH_TOKEN_STRATEGY', 'VIEW_PIPELINE_ADAPTER'
138
]
139
140
141
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...
142
    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...
143
        if explicit_overriden_settings is None:
144
            explicit_overriden_settings = {}
145
146
        overriden_settings = getattr(
147
            django_settings, DJOSER_SETTINGS_NAMESPACE, {}
148
        ) or explicit_overriden_settings
149
150
        self._load_default_settings()
151
        self._override_settings(overriden_settings)
152
        self._init_settings_to_import()
153
154
    def _load_default_settings(self):
155
        for setting_name, setting_value in six.iteritems(default_settings):
156
            if setting_name.isupper():
157
                setattr(self, setting_name, setting_value)
158
159
    def _override_settings(self, overriden_settings):
160
        for setting_name, setting_value in six.iteritems(overriden_settings):
161
            value = setting_value
162
            if isinstance(setting_value, dict):
163
                value = getattr(self, setting_name, {})
164
                value.update(ObjDict(setting_value))
165
            setattr(self, setting_name, value)
166
167
    def _init_settings_to_import(self):
168
        for setting_name in SETTINGS_TO_IMPORT:
169
            value = getattr(self, setting_name)
170
            if isinstance(value, str):
171
                setattr(self, setting_name, import_string(value))
172
173
174
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...
175
    def _setup(self, explicit_overriden_settings=None):
176
        self._wrapped = Settings(default_settings, explicit_overriden_settings)
0 ignored issues
show
Coding Style introduced by
The attribute _wrapped was defined outside __init__.

It is generally a good practice to initialize all attributes to default values in the __init__ method:

class Foo:
    def __init__(self, x=None):
        self.x = x
Loading history...
177
178
179
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...
180
181
182
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...
183
    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...
184
    setting, value = kwargs['setting'], kwargs['value']
185
    if setting == DJOSER_SETTINGS_NAMESPACE:
186
        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...
187
188
189
setting_changed.connect(reload_djoser_settings)
190