This repository has been archived by the owner on Aug 16, 2018. It is now read-only.
/
render.py
257 lines (197 loc) · 5.93 KB
/
render.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python
"""
Commands for rendering various parts of the app stack.
"""
import app
import app_config
import codecs
import os
from fabric.api import local, task
from glob import glob
def _fake_context(path):
"""
Create a fact request context for a given path.
"""
return app.app.test_request_context(path=path)
def _view_from_name(name):
"""
Determine what module a view resides in, then get
a reference to it.
"""
bits = name.split('.')
# Determine which module the view resides in
if len(bits) > 1:
module, name = bits
else:
module = 'app'
return globals()[module].__dict__[name]
@task
def less():
"""
Render LESS files to CSS.
"""
for path in glob('less/*.less'):
filename = os.path.split(path)[-1]
name = os.path.splitext(filename)[0]
out_path = 'www/css/%s.less.css' % name
try:
local('node_modules/less/bin/lessc %s %s' % (path, out_path))
except:
print 'It looks like "lessc" isn\'t installed. Try running: "npm install"'
raise
@task
def jst():
"""
Render Underscore templates to a JST package.
"""
try:
local('node_modules/universal-jst/bin/jst.js --template underscore jst www/js/templates.js')
except:
print 'It looks like "jst" isn\'t installed. Try running: "npm install"'
@task
def app_config_js():
"""
Render app_config.js to file.
"""
from static.blueprint import _app_config_js
with _fake_context('/js/app_config.js'):
response = _app_config_js()
with open('www/js/app_config.js', 'w') as f:
f.write(response.data)
@task
def copytext_js():
"""
Render COPY to copy.js.
"""
from static.blueprint import _copy_js
with _fake_context('/js/copytext.js'):
response = _copy_js()
with open('www/js/copy.js', 'w') as f:
f.write(response.data)
@task
def render_card_route(view_name, params=None):
from flask import url_for
path = view_name
if params:
path = '{0}/{1}/'.format(view_name, params)
else:
path = '{0}/'.format(view_name)
path = path.replace('_', '-')
with app.app.test_client() as client:
resp = client.get(path)
_write_file(path, resp.data)
@task
def render_results_json():
from flask import url_for
view_name = 'results_json'
electiondate = app_config.NEXT_ELECTION_DATE
with app.app.test_request_context():
path = url_for(view_name, electiondate=electiondate)
view = app.__dict__[view_name]
content = view(electiondate)
try:
os.makedirs('.cards_html/data')
except OSError:
pass
with codecs.open('.cards_html/{0}'.format(path), 'w', 'utf-8') as f:
f.write(content)
@task
def render_delegates_json():
from flask import url_for
view_name = 'delegates_json'
with app.app.test_request_context():
path = url_for(view_name)
view = app.__dict__[view_name]
content = view()
try:
os.makedirs('.cards_html/data')
except OSError:
pass
with codecs.open('.cards_html/{0}'.format(path), 'w', 'utf-8') as f:
f.write(content)
@task
def render_route(slug):
from flask import url_for
view_name = 'card'
with app.app.test_request_context():
full_path = url_for(view_name, slug=slug)
simplified_path = full_path.replace('/%s' % view_name, '')
with app.app.test_request_context(path=full_path):
view = app.__dict__[view_name]
content = view(slug)
_write_file(simplified_path, content)
@task()
def render_index():
"""
Render HTML templates and compile assets.
"""
from flask import g
with _fake_context('/'):
g.compile_includes = True
g.compiled_includes = {}
g.no_compress = True
view = _view_from_name('index')
content = view().data
_write_file('', content)
@task()
def render_current_state(folder='.cards_html'):
"""
Render HTML templates and compile assets.
"""
with _fake_context('/current-state.json'):
view = _view_from_name('current_state')
content = view().data
with codecs.open('%s/current-state.json' % folder, 'w', 'utf-8') as f:
f.write(content)
def _write_file(path, content):
path = os.path.join('.cards_html', path)
try:
os.makedirs(path)
except OSError:
pass
filepath = os.path.join(path, 'index.html')
with open(filepath, 'w') as f:
f.write(content)
@task(default=True)
def render_all():
"""
Render HTML templates and compile assets.
"""
from flask import g
less()
jst()
app_config_js()
copytext_js()
compiled_includes = {}
# Loop over all views in the app
for rule in app.app.url_map.iter_rules():
rule_string = rule.rule
name = rule.endpoint
# Skip utility views
if name != 'index':
print 'Skipping %s' % name
continue
# Convert trailing slashes to index.html files
if rule_string.endswith('/'):
filename = 'www' + rule_string + 'index.html'
elif rule_string.endswith('.html'):
filename = 'www' + rule_string
else:
print 'Skipping %s' % name
continue
# Create the output path
dirname = os.path.dirname(filename)
if not (os.path.exists(dirname)):
os.makedirs(dirname)
print 'Rendering %s' % (filename)
# Render views, reusing compiled assets
with _fake_context(rule_string):
g.compile_includes = True
g.compiled_includes = compiled_includes
view = _view_from_name(name)
content = view().data
compiled_includes = g.compiled_includes
# Write rendered view
# NB: Flask response object has utf-8 encoded the data
with open(filename, 'w') as f:
f.write(content)