Passed
Push — master ( 68a360...546f3a )
by Fabio
03:54
created

benedict.utils.io_util   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 30
dl 0
loc 44
rs 10
c 0
b 0
f 0

5 Functions

Rating   Name   Duplication   Size   Complexity  
A write_file() 0 13 4
A encode_json() 0 2 1
A read_url() 0 4 1
A decode_json() 0 3 2
A read_file() 0 5 1
1
# -*- coding: utf-8 -*-
2
3
import errno
4
import json
5
import os
6
import requests
7
8
9
def decode_json(s, **kwargs):
10
    data = json.loads(s, **kwargs)
11
    return { 'values':data } if isinstance(data, list) else data
12
13
14
def encode_json(d, **kwargs):
15
    return json.dumps(d, **kwargs)
16
17
18
def read_file(filepath):
19
    handler = open(filepath, 'r')
20
    content = handler.read()
21
    handler.close()
22
    return content
23
24
25
def read_url(url, *args, **kwargs):
26
    response = requests.get(url, *args, **kwargs)
27
    content = response.text
28
    return content
29
30
31
def write_file(filepath, content):
32
    # https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output
33
    if not os.path.exists(os.path.dirname(filepath)):
34
        try:
35
            os.makedirs(os.path.dirname(filepath))
36
        except OSError as e:
37
            # Guard against race condition
38
            if e.errno != errno.EEXIST:
39
                raise e
40
    handler = open(filepath, 'w+')
41
    handler.write(content)
42
    handler.close()
43
    return True
44