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
|
|
|
|