Passed
Push — master ( db2481...3bd527 )
by Fabio
03:28
created

benedict.dicts.io.io_util   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 17
eloc 60
dl 0
loc 83
rs 10
c 0
b 0
f 0

7 Functions

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