GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

get_object_from_classbased_instance()   F
last analyzed

Complexity

Conditions 11

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
c 1
b 0
f 0
dl 0
loc 52
rs 3.8571

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like get_object_from_classbased_instance() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# coding=utf-8
2
"""
3
permission_required decorator for generic classbased view from django 1.3
4
"""
5
from functools import wraps
6
from django.utils.decorators import available_attrs
7
from django.core.exceptions import PermissionDenied
8
from permission.decorators.utils import redirect_to_login
9
10
11
def permission_required(perm, queryset=None,
12
                        login_url=None, raise_exception=False):
13
    """
14
    Permission check decorator for classbased generic view
15
16
    This decorator works as class decorator
17
    DO NOT use ``method_decorator`` or whatever while this decorator will use
18
    ``self`` argument for method of classbased generic view.
19
20
    Parameters
21
    ----------
22
    perm : string
23
        A permission string
24
    queryset : queryset or model
25
        A queryset or model for finding object.
26
        With classbased generic view, ``None`` for using view default queryset.
27
        When the view does not define ``get_queryset``, ``queryset``,
28
        ``get_object``, or ``object`` then ``obj=None`` is used to check
29
        permission.
30
        With functional generic view, ``None`` for using passed queryset.
31
        When non queryset was passed then ``obj=None`` is used to check
32
        permission.
33
34
    Examples
35
    --------
36
    >>> @permission_required('auth.change_user')
37
    >>> class UpdateAuthUserView(UpdateView):
38
    ...     pass
39
    """
40
    def wrapper(cls):
41
        def view_wrapper(view_func):
42
            @wraps(view_func, assigned=available_attrs(view_func))
43
            def inner(self, request, *args, **kwargs):
44
                # get object
45
                obj = get_object_from_classbased_instance(
46
                        self, queryset, request, *args, **kwargs
47
                    )
48
49
                if not request.user.has_perm(perm, obj=obj):
50
                    if raise_exception:
51
                        raise PermissionDenied
52
                    else:
53
                        return redirect_to_login(request, login_url)
54
                return view_func(self, request, *args, **kwargs)
55
            return inner
56
        cls.dispatch = view_wrapper(cls.dispatch)
57
        return cls
58
    return wrapper
59
60
61
def get_object_from_classbased_instance(
62
        instance, queryset, request, *args, **kwargs):
63
    """
64
    Get object from an instance of classbased generic view
65
66
    Parameters
67
    ----------
68
    instance : instance
69
        An instance of classbased generic view
70
    queryset : instance
71
        A queryset instance
72
    request : instance
73
        A instance of HttpRequest
74
75
    Returns
76
    -------
77
    instance
78
        An instance of model object or None
79
    """
80
    from django.views.generic.edit import BaseCreateView
81
    # initialize request, args, kwargs of classbased_instance
82
    # most of methods of classbased view assumed these attributes
83
    # but these attributes is initialized in ``dispatch`` method.
84
    instance.request = request
85
    instance.args = args
86
    instance.kwargs = kwargs
87
88
    # get queryset from class if ``queryset_or_model`` is not specified
89
    if hasattr(instance, 'get_queryset') and not queryset:
90
        queryset = instance.get_queryset()
91
    elif hasattr(instance, 'queryset') and not queryset:
92
        queryset = instance.queryset
93
    elif hasattr(instance, 'model') and not queryset:
94
        queryset = instance.model._default_manager.all()
95
96
    # get object
97
    if hasattr(instance, 'get_object'):
98
        try:
99
            obj = instance.get_object(queryset)
100
        except AttributeError as e:
101
            # CreateView has ``get_object`` method but CreateView
102
            # should not have any object before thus simply set
103
            # None
104
            if isinstance(instance, BaseCreateView):
105
                obj = None
106
            else:
107
                raise e
108
    elif hasattr(instance, 'object'):
109
        obj = instance.object
110
    else:
111
        obj = None
112
    return obj
113
114