Total Complexity | 9 |
Total Lines | 44 |
Duplicated Lines | 0 % |
Changes | 0 |
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 |