|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
|
|
3
|
|
|
import errno |
|
4
|
|
|
import json |
|
5
|
|
|
import os |
|
6
|
|
|
import requests |
|
7
|
|
|
import xmltodict |
|
8
|
|
|
import toml |
|
9
|
|
|
import yaml |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
def decode_json(s, **kwargs): |
|
13
|
|
|
data = json.loads(s, **kwargs) |
|
14
|
|
|
return data |
|
15
|
|
|
|
|
16
|
|
|
|
|
17
|
|
|
def decode_xml(s, **kwargs): |
|
18
|
|
|
kwargs.setdefault('dict_constructor', dict) |
|
19
|
|
|
data = xmltodict.parse(s, **kwargs) |
|
20
|
|
|
return data |
|
21
|
|
|
|
|
22
|
|
|
|
|
23
|
|
|
def decode_toml(s, **kwargs): |
|
24
|
|
|
data = toml.loads(s, **kwargs) |
|
25
|
|
|
return data |
|
26
|
|
|
|
|
27
|
|
|
|
|
28
|
|
|
def decode_yaml(s, **kwargs): |
|
29
|
|
|
kwargs.setdefault('Loader', yaml.Loader) |
|
30
|
|
|
data = yaml.load(s, **kwargs) |
|
31
|
|
|
return data |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
def encode_json(d, **kwargs): |
|
35
|
|
|
data = json.dumps(d, **kwargs) |
|
36
|
|
|
return data |
|
37
|
|
|
|
|
38
|
|
|
|
|
39
|
|
|
def encode_toml(d, **kwargs): |
|
40
|
|
|
data = toml.dumps(d, **kwargs) |
|
41
|
|
|
return data |
|
42
|
|
|
|
|
43
|
|
|
|
|
44
|
|
|
def encode_xml(d, **kwargs): |
|
45
|
|
|
data = xmltodict.unparse(d, **kwargs) |
|
46
|
|
|
return data |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
def encode_yaml(d, **kwargs): |
|
50
|
|
|
data = yaml.dump(d, **kwargs) |
|
51
|
|
|
return data |
|
52
|
|
|
|
|
53
|
|
|
|
|
54
|
|
|
def read_file(filepath): |
|
55
|
|
|
handler = open(filepath, 'r') |
|
56
|
|
|
content = handler.read() |
|
57
|
|
|
handler.close() |
|
58
|
|
|
return content |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
def read_url(url, *args, **kwargs): |
|
62
|
|
|
response = requests.get(url, *args, **kwargs) |
|
63
|
|
|
content = response.text |
|
64
|
|
|
return content |
|
65
|
|
|
|
|
66
|
|
|
|
|
67
|
|
|
def write_file(filepath, content): |
|
68
|
|
|
# https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output |
|
69
|
|
|
if not os.path.exists(os.path.dirname(filepath)): |
|
70
|
|
|
try: |
|
71
|
|
|
os.makedirs(os.path.dirname(filepath)) |
|
72
|
|
|
except OSError as e: |
|
73
|
|
|
# Guard against race condition |
|
74
|
|
|
if e.errno != errno.EEXIST: |
|
75
|
|
|
raise e |
|
76
|
|
|
handler = open(filepath, 'w+') |
|
77
|
|
|
handler.write(content) |
|
78
|
|
|
handler.close() |
|
79
|
|
|
return True |
|
80
|
|
|
|