source: trunk/renderer.py

Last change on this file was 20, checked in by JohnLightfoot, 10 years ago

bug fixes

File size: 2.8 KB
Line 
1from __future__ import absolute_import
2
3import collections
4import datetime
5import os
6import shutil
7
8from extern import mako
9from mako.template import Template
10from mako.lookup import TemplateLookup
11
12import templates
13import templates.resources as resources
14
15
16class Renderer(object):
17 """Class to render results into html.
18 """
19
20 def __init__(self, result):
21 self.result = result
22
23 def copy_resources(self, dirname):
24 outdir = os.path.join(dirname, 'resources')
25
26 # shutil.copytree complains if the output directory exists
27 if os.path.exists(outdir):
28 shutil.rmtree(outdir)
29
30 # copy all uncompressed non-python resources to output directory
31 src = os.path.dirname(resources.__file__)
32 dst = outdir
33 ignore_fn = shutil.ignore_patterns('*.zip','*.py','*.pyc','CVS*')
34 shutil.copytree(src,
35 dst,
36 symlinks=False,
37 ignore=ignore_fn)
38
39# # unzip fancybox to output directory
40# infile = os.path.join(src, 'fancybox.zip')
41# z = zipfile.ZipFile(infile, 'r')
42# z.extractall(outdir)
43
44 def run(self):
45 # make a directory to contain this result
46 now = datetime.datetime.today()
47 dirname = 'fisica-%s' % (now.strftime('%Y%m%dT%H%M%S'))
48 os.mkdir(dirname)
49
50 # make a resources directory and copy the Bootstrap stuff there
51 self.copy_resources(dirname)
52
53 # where to find the template files
54 templates_dir = os.path.dirname(templates.__file__)
55 mylookup = TemplateLookup(directories=[templates_dir])
56
57 # render the simulation steps first
58 for stage in self.result.items():
59 if 'substages' in stage[1].keys():
60 for substage in stage[1]['substages'].items():
61 print 'rendering', stage[0], substage[0]
62 context = {'dirname':dirname, 'renderstage':stage[0],
63 'rendersubstage':substage[0], 'data':self.result}
64
65 link = os.path.join(context['dirname'], '%s-%s.html' % (stage[0], substage[0]))
66 with open(link, 'w') as f:
67 template = mylookup.get_template('%s-%s.html' % (stage[0], substage[0]))
68 f.write(template.render(**context))
69
70 else:
71 # no substages
72 print 'rendering', stage[0]
73 context = {'mylookup':mylookup, 'dirname':dirname,
74 'renderstage':stage[0],
75 'data':self.result}
76
77 link = os.path.join(context['dirname'], '%s.html' % (stage[0]))
78 with open(link, 'w') as f:
79 template = mylookup.get_template('%s.html' % (stage[0]))
80 f.write(template.render(**context))
81
Note: See TracBrowser for help on using the repository browser.