Conditions | 8 |
Total Lines | 54 |
Lines | 0 |
Ratio | 0 % |
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:
If many parameters/temporary variables are present:
1 | # coding=utf-8 |
||
13 | def permission_required(perm, queryset=None, |
||
14 | login_url=None, raise_exception=False): |
||
15 | """ |
||
16 | Permission check decorator for function-base generic view |
||
17 | |||
18 | This decorator works as function decorator |
||
19 | |||
20 | Parameters |
||
21 | ---------- |
||
22 | perm : string |
||
23 | A permission string |
||
24 | queryset_or_model : 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 | >>> def update_auth_user(request, *args, **kwargs): |
||
38 | ... pass |
||
39 | """ |
||
40 | def wrapper(view_func): |
||
41 | @wraps(view_func, assigned=available_attrs(view_func)) |
||
42 | def inner(request, *args, **kwargs): |
||
43 | _kwargs = copy.copy(kwargs) |
||
44 | # overwrite queryset if specified |
||
45 | if queryset: |
||
46 | _kwargs['queryset'] = queryset |
||
47 | |||
48 | # get object from view |
||
49 | if 'date_field' in _kwargs: |
||
50 | fn = get_object_from_date_based_view |
||
51 | else: |
||
52 | fn = get_object_from_list_detail_view |
||
53 | if fn.validate(request, *args, **_kwargs): |
||
54 | obj = fn(request, *args, **_kwargs) |
||
55 | else: |
||
56 | # required arguments is not passed |
||
57 | obj = None |
||
58 | |||
59 | if not request.user.has_perm(perm, obj=obj): |
||
60 | if raise_exception: |
||
61 | raise PermissionDenied |
||
62 | else: |
||
63 | return redirect_to_login(request, login_url) |
||
64 | return view_func(request, *args, **_kwargs) |
||
65 | return inner |
||
66 | return wrapper |
||
67 | |||
182 |