Completed
Push — master ( c4eb3d...d2294e )
by Chris
01:17
created

require_args()   F

Complexity

Conditions 10

Size

Total Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
c 2
b 0
f 0
dl 0
loc 38
rs 3.1304

How to fix   Complexity   

Complexity

Complex classes like require_args() 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
"""App view decorators."""
2
3
from functools import wraps
4
5
from flask import request
6
7
8 View Code Duplication
def require_headers(headers=[]):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
9
    """Check for required headers in a view.
10
11
    @require_headers(headers=['X-Foo'])
12
    @def view():
13
        pass
14
    """
15
    def outer(func, *args, **kwargs):
16
        @wraps(func)
17
        def inner(*args, **kwargs):
18
            if headers:
19
                s1, s2 = set(headers), set([h[0] for h in request.headers])
20
                matches = s1.intersection(s2)
21
                diff = s1.difference(s2)
22
                if len(s1) != len(matches):
23
                    raise ValueError(
24
                        'Missing required header(s): {}'.format(list(diff)))
25
            return func(*args, **kwargs)
26
        return inner
27
    return outer
28
29
30 View Code Duplication
def require_cookies(cookies=[]):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
31
    """Check for required cookies in a view.
32
33
    @require_cookies(cookies=['csrftoken', 'session'])
34
    @def view():
35
        pass
36
    """
37
    def outer(func, *args, **kwargs):
38
        @wraps(func)
39
        def inner(*args, **kwargs):
40
            if cookies:
41
                s1 = set(cookies)
42
                s2 = set([k for k, v in request.cookies.items()])
43
                matches = s1.intersection(s2)
44
                diff = s1.difference(s2)
45
                if len(s1) != len(matches):
46
                    raise ValueError(
47
                        'Missing required cookie(s): {}'.format(list(diff)))
48
            return func(*args, **kwargs)
49
        return inner
50
    return outer
51
52
53
def require_args(params=[]):
54
    """Check for required args (and values) in a view.
55
56
    @require_args(params=['paginate'])
57
    @def view():
58
        pass
59
60
    or, if you want to check both key and value:
61
62
    @require_args(params={'paginate': True})
63
    @def view():
64
        pass
65
    """
66
    def outer(func, *args, **kwargs):
67
        @wraps(func)
68
        def inner(*args, **kwargs):
69
            if params:
70
                if isinstance(params, list):
71
                    s1 = set(params)
72
                    s2 = set([k for k, v in request.args.items()])
73
                    matches = s1.intersection(s2)
74
                    diff = s1.difference(s2)
75
                    if len(s1) != len(matches):
76
                        raise ValueError(
77
                            'Missing required arg(s): {}'.format(list(diff)))
78
                else:
79
                    for param, val in params.items():
80
                        arg = request.args.get(param, None)
81
                        if arg is None:
82
                            raise ValueError(
83
                                'Missing param `{}`'.format(param))
84
                        if arg != val:
85
                            raise ValueError(
86
                                'Invalid value `{}` '
87
                                'for param {}.'.format(arg, param))
88
            return func(*args, **kwargs)
89
        return inner
90
    return outer
91