Conditions | 8 |
Total Lines | 55 |
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 | import logging |
||
35 | def encode(self, |
||
36 | msg, |
||
37 | delimiter='.', |
||
38 | prefix='', |
||
39 | prefix_tag=None, |
||
40 | postfix='', |
||
41 | postfix_tag=None, |
||
42 | ): |
||
43 | """ |
||
44 | :param msg: Payload from reader |
||
45 | :param delimiter: Delimiter between Graphite series parts |
||
46 | :param prefix: Graphite prefix string |
||
47 | :param prefix_tag: Tag to use for Graphite prefix |
||
48 | :param postfix: Graphite postfix string |
||
49 | :param postfix_tag: Tag to use for Graphite postfix |
||
50 | :return: A list of encoded messages |
||
51 | """ |
||
52 | # One message could consist of several measurements |
||
53 | measurements = [] |
||
54 | |||
55 | for line in msg.decode().split("\n"): |
||
56 | try: |
||
57 | series, value, timestamp = line.split() |
||
58 | except ValueError as e: |
||
59 | logging.debug("Error in encoder: %s", e) |
||
60 | continue |
||
61 | # Strip prefix and postfix: |
||
62 | series = series[len(prefix):len(series) - len(postfix)] |
||
63 | # Split into tags |
||
64 | hostname, measurement = series.split(delimiter, 1) |
||
65 | measurement = measurement.replace(delimiter, '_') |
||
66 | |||
67 | tags = { |
||
68 | "host": hostname |
||
69 | } |
||
70 | if prefix_tag: |
||
71 | if prefix.endswith(delimiter): |
||
72 | prefix = prefix[:-len(delimiter)] |
||
73 | tags[prefix_tag] = prefix |
||
74 | if postfix_tag: |
||
75 | if postfix.endswith(delimiter): |
||
76 | postfix = postfix[:-len(delimiter)] |
||
77 | tags[postfix_tag] = postfix |
||
78 | |||
79 | encoded = ''.join([ |
||
80 | str(measurement), |
||
81 | ',', |
||
82 | ','.join('{}={}'.format(self.escape_tag(k), self.escape_tag(tags[k])) for k in tags), |
||
83 | ' value=', |
||
84 | str(value), |
||
85 | ' ', |
||
86 | timestamp |
||
87 | ]) |
||
88 | measurements.append(encoded) |
||
89 | return measurements |
||
90 |