/
application.py
162 lines (112 loc) · 3.37 KB
/
application.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
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# HTTP server and templating
import http.server
from jinja2 import Template
# mincss
from os.path import abspath, dirname, join, normpath
from mincss.processor import Processor, ParserError
import lxml.html
from lxml import etree
from lxml.cssselect import CSSSelector
# Minification and compression
from rcssmin import cssmin
from slimit import minify
import base64
import re
PROJECT_ROOT = dirname(abspath(__file__))
SERVER_PORT = 9000
STYLESHEETS = [
"static/css/bootstrap.min.css",
"static/css/app.css",
]
SCRIPTS = [
"static/js/sha1.js",
"static/js/app.js",
]
IMAGES = {
"icon": "static/img/padlock.png",
}
def process_html(html):
mini_html = html
mini_html = re.sub(r'(\r\n|\n|\r|\t)', '', mini_html, flags=re.M)
mini_html = re.sub(r'\s+', ' ', mini_html, flags=re.M)
return mini_html
def process_css(html, stylesheets):
p = Processor()
parser = etree.HTMLParser()
tree = etree.fromstring(html, parser).getroottree()
page = tree.getroot()
if page is None:
print(repr(html))
raise ParserError("Could not parse the HTML")
body, = CSSSelector('body')(page)
processed_css = ''
for sheet in stylesheets:
sheet_path = normpath(join(PROJECT_ROOT, sheet))
with open(sheet_path, 'r') as sheet_file:
content = sheet_file.read()
processed_css += p._process_content(content, [body, ])
return cssmin(processed_css)
def process_js(scripts):
aggregated_scripts = ''
for script in scripts:
script_path = normpath(join(PROJECT_ROOT, script))
with open(script_path, 'r') as script_file:
aggregated_scripts += script_file.read()
return minify(aggregated_scripts, mangle=True, mangle_toplevel=True)
def process_images(images):
processed_images = {}
for key, image in images.items():
with open(images[key], "rb") as image_file:
image_data = image_file.read()
encoded_string = base64.standard_b64encode(image_data)
processed_images[key] = "data:image/png;base64," + encoded_string.decode('utf-8')
return processed_images
class Handler(http.server.SimpleHTTPRequestHandler):
extensions_map = {
'.css': 'text/css',
'.html': 'text/html',
'.js': 'text/javascript',
'.png': 'image/png',
}
def get_template(self):
template_path = normpath(join(PROJECT_ROOT, 'templates/password.html'))
with open(template_path) as tpl:
template = Template(tpl.read())
return template
def get_html(self):
template = self.get_template()
return template.render(
stylesheets=STYLESHEETS,
scripts=SCRIPTS,
images=IMAGES
)
def get_compressed(self):
template = self.get_template()
raw_html = template.render(images={})
html = template.render(
inline_style=process_css(raw_html, STYLESHEETS),
inline_script=process_js(SCRIPTS),
images=process_images(IMAGES),
)
return process_html(html)
def do_GET(self):
if self.path.startswith("/static"):
return super().do_GET()
html = None
if self.path == "/":
html = self.get_html()
if self.path.startswith("/compress"):
html = self.get_compressed()
if html is not None:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(html, 'utf-8'))
return
self.send_error(404, "File Not Found %s" % self.path)
if __name__ == "__main__":
try:
server = http.server.HTTPServer(("", SERVER_PORT), Handler) # listen on all interfaces
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()