| Conditions | 11 |
| Total Lines | 29 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Complex classes like encode_image_from_url() 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 -*- |
||
| 16 | def encode_image_from_url(url, source_path): |
||
| 17 | if not url or url.startswith('data:') or url.startswith('file://'): |
||
| 18 | return False |
||
| 19 | |||
| 20 | if url.startswith('http://') or url.startswith('https://'): |
||
| 21 | return False |
||
| 22 | |||
| 23 | real_path = url if os.path.isabs(url) else os.path.join(source_path, url) |
||
| 24 | |||
| 25 | if not os.path.exists(real_path): |
||
| 26 | print('%s was not found, skipping' % url) |
||
| 27 | |||
| 28 | return False |
||
| 29 | |||
| 30 | mime_type, encoding = mimetypes.guess_type(real_path) |
||
| 31 | |||
| 32 | if not mime_type: |
||
| 33 | print('Unrecognized mime type for %s, skipping' % url) |
||
| 34 | |||
| 35 | return False |
||
| 36 | |||
| 37 | try: |
||
| 38 | with open(real_path, 'rb') as image_file: |
||
| 39 | image_contents = image_file.read() |
||
| 40 | encoded_image = base64.b64encode(image_contents) |
||
| 41 | except IOError: |
||
| 42 | return False |
||
| 43 | |||
| 44 | return u"data:%s;base64,%s" % (mime_type, encoded_image.decode()) |
||
| 45 |