-
Notifications
You must be signed in to change notification settings - Fork 3
/
run
executable file
·140 lines (121 loc) · 4.85 KB
/
run
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/python3
import json
import os
import shlex
import subprocess
import sys
import threading
from http.server import ThreadingHTTPServer
from http.server import SimpleHTTPRequestHandler
sys.path.append("scripts")
import data_util
MAPBOX_API_VARNAME = "MAPBOX_API_TOKEN"
with open("config.json") as f:
CONFIG = json.loads(f.read())
f.close()
if len(sys.argv) < 3:
my_name = os.path.basename(__file__)
print(f"Usage: {my_name} disease environment")
print(f"E.g. {my_name} covid-19 prod")
sys.exit(1)
DISEASE_ID = sys.argv[1]
DEPLOY_ENV = sys.argv[2]
if DEPLOY_ENV not in ['dev', 'prod']:
print(f"Deployment environment must be dev or prod, not {DEPLOY_ENV}")
sys.exit(1)
class VizHandler(SimpleHTTPRequestHandler):
def send_head(self):
line_list_url = CONFIG[DISEASE_ID]["prod_line_list_url"] if DEPLOY_ENV == 'prod' else CONFIG[DISEASE_ID]["dev_line_list_url"]
data_src_url = CONFIG[DISEASE_ID]["prod_data_src_url"] if DEPLOY_ENV == 'prod' else CONFIG[DISEASE_ID]["dev_data_src_url"]
path = self.translate_path(self.path)
if "favicon.ico" in path:
self.send_response(404)
self.end_headers()
return None
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
binary = path.endswith(".gif") or path.endswith(".png")
f = open(path, "rb" if binary else "r")
contents = f.read()
# there are many JS files that use the line list url, so always do this substitution
if ".js" in self.path:
contents = contents.replace("{{LINE_LIST_URL}}",
line_list_url)
if "diseasemap.js" in self.path:
if MAPBOX_API_VARNAME in os.environ:
contents = contents.replace("{{MAPBOX_API_TOKEN}}",
os.environ[MAPBOX_API_VARNAME])
if "sidebar.js" in self.path or "view.js" in self.path:
contents = contents.replace(
"{{TITLE}}", CONFIG[DISEASE_ID]["name"])
if "sidebar.js" in self.path:
other_diseases = []
for disease_id in CONFIG[DISEASE_ID]["linkto"]:
other_diseases.append("|".join([
disease_id, CONFIG[disease_id]["name"], CONFIG[disease_id]["url"]]))
contents = contents.replace(
"{{OTHER_DISEASES}}", ",".join(other_diseases))
if "main.js" in self.path:
if not data_src_url.endswith("/"):
data_src_url += "/"
contents = contents.replace("{{DATA_SRC_URL}}", data_src_url)
encoded_contents = contents if binary else contents.encode()
ctype = self.guess_type(path)
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(len(encoded_contents)))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
self.wfile.write(encoded_contents)
# We've taken care of everything, nothing left to do.
return None
# Returns True if everything we need for sass is here, False otherwise.
def check_sass():
try:
subprocess.check_call(shlex.split("sass --version"))
except (subprocess.CalledProcessError, OSError):
print("WARNING: 'sass' is not installed, CSS will not update on the fly")
return False
return True
def run_sass_precompiler():
input_files = [f for f in os.listdir("css") if f.endswith(".scss")]
if not len(input_files):
return None
return subprocess.call(shlex.split("sass --watch css:css"))
def run_http_server():
server = ThreadingHTTPServer(("localhost", 8000), VizHandler)
server.serve_forever()
def run():
data_util.make_country_pages()
if MAPBOX_API_VARNAME not in os.environ:
print("Please set the 'MAPBOX_API_TOKEN' to your development token. "
"Aborting.")
print(os.environ)
sys.exit(1)
try:
http = threading.Thread(target=run_http_server)
sass = threading.Thread(target=run_sass_precompiler)
http.start()
if check_sass():
sass.start()
sass.join()
http.join()
except KeyboardInterrupt:
print("Hit Ctrl-C a second time to shut down.")
sys.exit(0)
if __name__ == '__main__':
run()