-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.py
53 lines (40 loc) · 1.44 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to see if a path exists."""
return True if os.path.exists(path) else False
def ls(path):
"""The contents of a directory."""
return os.listdir(path)
def mkdir(path):
"""Create the given directory path if it doesn't already exist."""
os.makedirs(path, exist_ok=True)
return path
def urlopen_image(url):
"""Retrieve image data from the specified url."""
for attempt in range(net.retries):
try:
return urllib.request.urlopen(url).read()
except:
print("Error: Downloading image (retry in {}s)".format(net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")
def urlopen_json(url, task="Unknown task"):
"""Retrieve json data from the specified url."""
for attempt in range(net.retries):
try:
reply = urllib.request.urlopen(url)
reply = json.loads(reply.read().decode())
return reply["DATA"]["RECORD"]
except:
print("Error: {} (retry in {}s)".format(task, net.wait))
time.sleep(net.wait)
raise ConnectionError("Halted: Unable to access resource")