Conditions | 10 |
Total Lines | 61 |
Code Lines | 40 |
Lines | 0 |
Ratio | 0 % |
Changes | 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:
Complex classes like libs.analytics.Analytics.analyze() 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 | import ipaddress |
||
82 | async def analyze(self, data: dict): |
||
83 | """ |
||
84 | Do analysis from URL sent by message with databases |
||
85 | |||
86 | :param data: dict from message decoded |
||
87 | :return: dict to response |
||
88 | """ |
||
89 | url = url_normalize(data.get("url")) |
||
90 | |||
91 | result_from_db = await self.check_from_database(url) |
||
92 | if result_from_db is not None: |
||
93 | return { |
||
94 | "status": 200, |
||
95 | "url": url, |
||
96 | "trust_score": result_from_db |
||
97 | } |
||
98 | |||
99 | try: |
||
100 | response = requests.get(url) |
||
101 | except requests.exceptions.ConnectionError as e: |
||
102 | return { |
||
103 | "status": 403, |
||
104 | "reason": str(e) |
||
105 | } |
||
106 | |||
107 | if response.status_code != 200: |
||
108 | return { |
||
109 | "status": 404, |
||
110 | "http_code": response.status_code |
||
111 | } |
||
112 | |||
113 | if "text/html" not in response.headers["content-type"]: |
||
114 | return { |
||
115 | "status": 405 |
||
116 | } |
||
117 | |||
118 | url = response.url |
||
119 | |||
120 | host = urlparse(url).hostname if urlparse( |
||
121 | url |
||
122 | ).hostname != "localhost" else "127.0.0.1" |
||
123 | |||
124 | if (validators.ipv4(host) or validators.ipv6(host)) and \ |
||
125 | ipaddress.ip_address(host).is_private: |
||
126 | return { |
||
127 | "status": 403, |
||
128 | "reason": "forbidden" |
||
129 | } |
||
130 | |||
131 | result_from_db = await self.check_from_database(url, host) |
||
132 | if result_from_db is not None: |
||
133 | return { |
||
134 | "status": 200, |
||
135 | "url": url, |
||
136 | "trust_score": result_from_db |
||
137 | } |
||
138 | |||
139 | return { |
||
140 | "status": 200, |
||
141 | "url": url, |
||
142 | "trust_score": await self._deep_analyze(url) |
||
143 | } |
||
225 |