SentryExceptionHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 56
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A clean_environment() 0 12 4
A __init__() 0 2 1
A __call__() 0 21 1
A guess_user_ip_from_request() 0 15 3
1
class SentryExceptionHandler:
2
    exclude = type(None)
3
4
    def __init__(self, client):
5
        self.client = client
6
7
    def __call__(self, request, response, exception):
8
        data = {
9
            'request': {
10
                'url': request.url,
11
                'method': request.method,
12
                'query_string': request.query_string,
13
                'headers': list(request.headers.items()),
14
                'cookies': list(request.cookies.items()),
15
                'env': self.clean_environment(request.env)
16
            },
17
            'user': {
18
                # 'id': 'testuser',
19
                # 'username': 'fkochem',
20
                'ip_address': self.guess_user_ip_from_request(request)
21
                # 'email': '[email protected]'
22
            }
23
        }
24
25
        self.client.captureException(data=data)
26
27
        raise exception
28
29
    def clean_environment(self, env):
30
        """
31
        Only keep 'REMOTE_ADDR' and environment attributes which begin
32
        with 'SERVER_'.
33
        """
34
        cleaned_env = {}
35
36
        for key, value in env.items():
37
            if key.startswith('SERVER_') or key == 'REMOTE_ADDR':
38
                cleaned_env[key] = value
39
40
        return cleaned_env
41
42
    def guess_user_ip_from_request(self, request):
43
        """
44
        Return 'X-FORWARDED-FOR' from the request headers if set,
45
        otherwise return 'REMOTE_ADDR' from the environment. If both are
46
        not set, return '127.0.0.1'.
47
        """
48
        forwarded_for = request.headers.get('X-FORWARDED-FOR', None)
49
        if forwarded_for:
50
            return forwarded_for
51
52
        remote_addr = request.env.get('REMOTE_ADDR', None)
53
        if remote_addr:
54
            return remote_addr
55
56
        return '127.0.0.1'
57