Completed
Push — master ( e6e2ec...0ced3f )
by Fabio
01:26
created

benedict.utils.io_util   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 84
rs 10
c 0
b 0
f 0
wmc 16

6 Functions

Rating   Name   Duplication   Size   Complexity  
A encode() 0 7 2
A write_file() 0 14 4
A read_content() 0 20 5
A read_url() 0 9 2
A read_file() 0 5 1
A decode() 0 8 2
1
# -*- coding: utf-8 -*-
2
3
from benedict.serializers import (
4
    get_serializer_by_format, get_serializers_extensions, )
5
6
import errno
7
import os
8
import requests
9
10
11
def decode(s, format, **kwargs):
12
    serializer = get_serializer_by_format(format)
13
    if serializer:
14
        decode_opts = kwargs.copy()
15
        data = serializer.decode(s.strip(), **decode_opts)
16
        return data
17
    else:
18
        raise ValueError('Invalid format: {}.'.format(format))
19
20
21
def encode(d, format, **kwargs):
22
    serializer = get_serializer_by_format(format)
23
    if serializer:
24
        s = serializer.encode(d, **kwargs)
25
        return s
26
    else:
27
        raise ValueError('Invalid format: {}.'.format(format))
28
29
30
def read_content(s):
31
    # s -> filepath or url or data
32
    num_lines = len(s.splitlines())
33
    if num_lines > 1:
34
        # data
35
        return s
36
    if any([s.startswith(protocol)
37
            for protocol in ['http://', 'https://']]):
38
        # url
39
        return read_url(s)
40
    elif any([s.endswith(extension)
41
              for extension in get_serializers_extensions()]):
42
        # filepath
43
        if os.path.isfile(s):
44
            return read_file(s)
45
        else:
46
            return None
47
    else:
48
        # data
49
        return s
50
51
52
def read_file(filepath):
53
    handler = open(filepath, 'r')
54
    content = handler.read()
55
    handler.close()
56
    return content
57
58
59
def read_url(url, *args, **kwargs):
60
    response = requests.get(url, *args, **kwargs)
61
    if response.status_code == requests.codes.ok:
62
        content = response.text
63
        return content
64
    else:
65
        raise ValueError(
66
            'Invalid url response status code: {}.'.format(
67
                response.status_code))
68
69
70
def write_file(filepath, content):
71
    # https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output
72
    filedir = os.path.dirname(filepath)
73
    if not os.path.exists(filedir):
74
        try:
75
            os.makedirs(filedir)
76
        except OSError as e:
77
            # Guard against race condition
78
            if e.errno != errno.EEXIST:
79
                raise e
80
    handler = open(filepath, 'w+')
81
    handler.write(content)
82
    handler.close()
83
    return True
84