Completed
Push — develop ( ce1198...1cbae8 )
by Kale
9s
created

stringify()   F

Complexity

Conditions 16

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 16
c 5
b 1
f 0
dl 0
loc 52
rs 3.0367

3 Methods

Rating   Name   Duplication   Size   Complexity  
A requests_models_PreparedRequest_builder() 0 9 3
A bottle_builder() 0 10 3
B requests_models_Response_builder() 0 13 5

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 stringify() 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
from __future__ import absolute_import, division, print_function, unicode_literals
3
from json import JSONEncoder
4
from logging import getLogger, INFO, Handler, Formatter, StreamHandler, DEBUG
5
from pprint import pformat
6
from sys import stderr
7
8
log = getLogger(__name__)
9
root_log = getLogger()
10
11
DEBUG_FORMATTER = Formatter(
12
    "[%(levelname)s] [%(asctime)s.%(msecs)03d] %(process)d %(name)s:%(funcName)s(%(lineno)d):\n"
13
    "%(message)s\n",
14
    "%Y-%m-%d %H:%M:%S")
15
16
INFO_FORMATTER = Formatter(
17
    "[%(levelname)s] [%(asctime)s.%(msecs)03d] %(process)d %(name)s(%(lineno)d): %(message)s\n",
18
    "%Y-%m-%d %H:%M:%S")
19
20
21
def set_root_level(level=INFO):
22
    root_log.setLevel(level)
23
24
25
def attach_stderr(level=INFO):
26
    has_stderr_handler = any(handler.name == 'stderr' for handler in root_log.handlers)
27
    if not has_stderr_handler:
28
        handler = StreamHandler(stderr)
29
        handler.name = 'stderr'
30
        if level is not None:
31
            handler.setLevel(level)
32
        handler.setFormatter(DEBUG_FORMATTER if level == DEBUG else INFO_FORMATTER)
33
        root_log.addHandler(handler)
34
        return True
35
    else:
36
        return False
37
38
39
def detach_stderr():
40
    for handler in root_log.handlers:
41
        if handler.name == 'stderr':
42
            root_log.removeHandler(handler)
43
            return True
44
    return False
45
46
47
def initialize_logging(level=INFO):
48
    attach_stderr(level)
49
50
51
class NullHandler(Handler):
52
    def emit(self, record):
53
        pass
54
55
56
class DumpEncoder(JSONEncoder):
57
    def default(self, obj):
58
        if hasattr(obj, 'dump'):
59
            return obj.dump()
60
        # Let the base class default method raise the TypeError
61
        return super(DumpEncoder, self).default(obj)
62
_DUMPS = DumpEncoder(indent=2, ensure_ascii=False, sort_keys=True).encode
63
64
65
def jsondumps(obj):
66
    return _DUMPS(obj)
67
68
69
def fullname(obj):
70
    return obj.__module__ + "." + obj.__class__.__name__
71
72
73
request_header_sort_dict = {
74
    'Host': '\x00\x00',
75
    'User-Agent': '\x00\x01',
76
}
77
def request_header_sort_key(item):  # NOQA
78
    return request_header_sort_dict.get(item[0], item[0].lower())
79
80
81
response_header_sort_dict = {
82
    'Content-Length': '\x7e\x7e\x61',
83
    'Connection': '\x7e\x7e\x62',
84
}
85
def response_header_sort_key(item):  # NOQA
86
    return response_header_sort_dict.get(item[0], item[0].lower())
87
88
89
def stringify(obj):
90
    def bottle_builder(builder, bottle_object):
91
        builder.append("{0} {1}{2} {3}".format(bottle_object.method,
92
                                               bottle_object.path,
93
                                               bottle_object.environ.get('QUERY_STRING', ''),
94
                                               bottle_object.get('SERVER_PROTOCOL')))
95
        builder += ["{0}: {1}".format(key, value) for key, value in bottle_object.headers.items()]
96
        builder.append('')
97
        body = bottle_object.body.read().strip()
98
        if body:
99
            builder.append(body)
100
101
    def requests_models_PreparedRequest_builder(builder, request_object):
102
        builder.append("> {0} {1} {2}".format(request_object.method, request_object.path_url,
103
                                              request_object.url.split(':', 1)[0].upper()))
104
        builder.extend("> {0}: {1}".format(key, value)
105
                       for key, value in sorted(request_object.headers.items(),
106
                                                key=request_header_sort_key))
107
        builder.append('')
108
        if request_object.body:
109
            builder.append(request_object.body)
110
111
    def requests_models_Response_builder(builder, response_object):
112
        builder.append("< {0} {1} {2}".format(response_object.url.split(':', 1)[0].upper(),
113
                                              response_object.status_code, response_object.reason))
114
        builder.extend("> {0}: {1}".format(key, value)
115
                       for key, value in sorted(response_object.headers.items(),
116
                                                key=response_header_sort_key))
117
        builder.append('')
118
        content_type = response_object.headers.get('Content-Type')
119
        if content_type == 'application/json':
120
            builder.append(pformat(response_object.json, indent=2))
121
            builder.append('')
122
        elif content_type is not None and content_type.startswith('text/'):
123
            builder.append(response_object.text)
124
125
    try:
126
        name = fullname(obj)
127
        builder = ['']  # start with new line
128
        if name.startswith('bottle.'):
129
            bottle_builder(builder, obj)
130
        elif name.endswith('requests.models.PreparedRequest'):
131
            requests_models_PreparedRequest_builder(builder, obj)
132
        elif name.endswith('requests.models.Response'):
133
            requests_models_PreparedRequest_builder(builder, obj.request)
134
            requests_models_Response_builder(builder, obj)
135
        else:
136
            return None
137
        builder.append('')  # end with new line
138
        return "\n".join(builder)
139
    except Exception as e:
140
        log.exception(e)
141