encode_image_from_url()   F
last analyzed

Complexity

Conditions 11

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
dl 0
loc 29
rs 3.1764
c 0
b 0
f 0

How to fix   Complexity   

Complexity

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 -*-
2
import base64
3
import mimetypes
4
import os
5
6
7
def get_path_url(path, relative=False):
8
    """ Returns an absolute or relative path url given a path
9
    """
10
    if relative is False:
11
        return 'file://%s' % os.path.abspath(path)
12
    else:
13
        return os.path.relpath(path, relative)
14
15
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