Debian Codegraph @

petl/io/html.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4
5 # standard library dependencies
6 import io
7 from petl.compat import text_type, numeric_types, next, PY2, izip_longest, \
8 string_types, callable
9
10
11 # internal dependencies
12 from petl.errors import ArgumentError
13 from petl.util.base import Table, Record
14 from petl.io.base import getcodec
15 from petl.io.sources import write_source_from_arg
16
17
18 def tohtml(table, source=None, encoding=None, errors='strict', caption=None,
19 vrepr=text_type, lineterminator='\n', index_header=False,
20 tr_style=None, td_styles=None, truncate=None):
21 """
22 Write the table as HTML to a file. E.g.::
23
24 >>> import petl as etl
25 >>> table1 = [['foo', 'bar'],
26 ... ['a', 1],
27 ... ['b', 2],
28 ... ['c', 2]]
29 >>> etl.tohtml(table1, 'example.html', caption='example table')
30 >>> print(open('example.html').read())
31 <table class='petl'>
32 <caption>example table</caption>
33 <thead>
34 <tr>
35 <th>foo</th>
36 <th>bar</th>
37 </tr>
38 </thead>
39 <tbody>
40 <tr>
41 <td>a</td>
42 <td style='text-align: right'>1</td>
43 </tr>
44 <tr>
45 <td>b</td>
46 <td style='text-align: right'>2</td>
47 </tr>
48 <tr>
49 <td>c</td>
50 <td style='text-align: right'>2</td>
51 </tr>
52 </tbody>
53 </table>
54
55 The `caption` keyword argument is used to provide a table caption
56 in the output HTML.
57
58 """
59
60 source = write_source_from_arg(source)
61 with source.open('wb') as buf:
62
63 # deal with text encoding
64 if PY2:
65 codec = getcodec(encoding)
66 f = codec.streamwriter(buf, errors=errors)
67 else:
68 f = io.TextIOWrapper(buf,
69 encoding=encoding,
70 errors=errors,
71 newline='')
72
73 # write the table
74 try:
75 it = iter(table)
76
77 # write header
78 try:
79 hdr = next(it)
80 except StopIteration:
81 hdr = []
82 _write_begin(f, hdr, lineterminator, caption, index_header,
83 truncate)
84
85 # write body
86 if tr_style and callable(tr_style):
87 # wrap as records
88 it = (Record(row, hdr) for row in it)
89 for row in it:
90 _write_row(f, hdr, row, lineterminator, vrepr,
91 tr_style, td_styles, truncate)
92
93 # finish up
94 _write_end(f, lineterminator)
95 f.flush()
96
97 finally:
98 if not PY2:
99 f.detach()
100
101
102 Table.tohtml = tohtml
103
104
105 def teehtml(table, source=None, encoding=None, errors='strict', caption=None,
106 vrepr=text_type, lineterminator='\n', index_header=False,
107 tr_style=None, td_styles=None, truncate=None):
108 """
109 Return a table that writes rows to a Unicode HTML file as they are
110 iterated over.
111
112 """
113
114 source = write_source_from_arg(source)
115 return TeeHTMLView(table, source=source, encoding=encoding, errors=errors,
116 caption=caption, vrepr=vrepr,
117 lineterminator=lineterminator, index_header=index_header,
118 tr_style=tr_style, td_styles=td_styles,
119 truncate=truncate)
120
121
122 Table.teehtml = teehtml
123
124
125 class TeeHTMLView(Table):
126 def __init__(self, table, source=None, encoding=None, errors='strict',
127 caption=None, vrepr=text_type, lineterminator='\n',
128 index_header=False, tr_style=None, td_styles=None,
129 truncate=None):
130 self.table = table
131 self.source = source
132 self.encoding = encoding
133 self.errors = errors
134 self.caption = caption
135 self.vrepr = vrepr
136 self.lineterminator = lineterminator
137 self.index_header = index_header
138 self.tr_style = tr_style
139 self.td_styles = td_styles
140 self.truncate = truncate
141
142 def __iter__(self):
143 table = self.table
144 source = self.source
145 encoding = self.encoding
146 errors = self.errors
147 lineterminator = self.lineterminator
148 caption = self.caption
149 index_header = self.index_header
150 tr_style = self.tr_style
151 td_styles = self.td_styles
152 vrepr = self.vrepr
153 truncate = self.truncate
154
155 with source.open('wb') as buf:
156
157 # deal with text encoding
158 if PY2:
159 codec = getcodec(encoding)
160 f = codec.streamwriter(buf, errors=errors)
161 else:
162 f = io.TextIOWrapper(buf,
163 encoding=encoding,
164 errors=errors,
165 newline='')
166
167 # write the table
168 try:
169 it = iter(table)
170
171 # write header
172 try:
173 hdr = next(it)
174 yield hdr
175 except StopIteration:
176 hdr = []
177 _write_begin(f, hdr, lineterminator, caption, index_header,
178 truncate)
179
180 # write body
181 if tr_style and callable(tr_style):
182 # wrap as records
183 it = (Record(row, hdr) for row in it)
184 for row in it:
185 _write_row(f, hdr, row, lineterminator, vrepr,
186 tr_style, td_styles, truncate)
187 yield row
188
189 # finish up
190 _write_end(f, lineterminator)
191 f.flush()
192
193 finally:
194 if not PY2:
195 f.detach()
196
197
198 def _write_begin(f, flds, lineterminator, caption, index_header, truncate):
199 f.write("<table class='petl'>" + lineterminator)
200 if caption is not None:
201 f.write(('<caption>%s</caption>' % caption) + lineterminator)
202 if flds:
203 f.write('<thead>' + lineterminator)
204 f.write('<tr>' + lineterminator)
205 for i, h in enumerate(flds):
206 if index_header:
207 h = '%s|%s' % (i, h)
208 if truncate:
209 h = h[:truncate]
210 f.write(('<th>%s</th>' % h) + lineterminator)
211 f.write('</tr>' + lineterminator)
212 f.write('</thead>' + lineterminator)
213 f.write('<tbody>' + lineterminator)
214
215
216 def _write_row(f, flds, row, lineterminator, vrepr, tr_style, td_styles,
217 truncate):
218 tr_css = _get_tr_css(row, tr_style)
219 if tr_css:
220 f.write(("<tr style='%s'>" % tr_css) + lineterminator)
221 else:
222 f.write("<tr>" + lineterminator)
223 for h, v in izip_longest(flds, row, fillvalue=None):
224 r = vrepr(v)
225 if truncate:
226 r = r[:truncate]
227 td_css = _get_td_css(h, v, td_styles)
228 if td_css:
229 f.write(("<td style='%s'>%s</td>" % (td_css, r)) + lineterminator)
230 else:
231 f.write(("<td>%s</td>" % r) + lineterminator)
232 f.write('</tr>' + lineterminator)
233
234
235 def _get_tr_css(row, tr_style):
236 # check for user-provided style
237 if tr_style:
238 if isinstance(tr_style, string_types):
239 return tr_style
240 elif callable(tr_style):
241 return tr_style(row)
242 else:
243 raise ArgumentError('expected string or callable, got %r'
244 % tr_style)
245 # fall back to default style
246 return ''
247
248
249 def _get_td_css(h, v, td_styles):
250 # check for user-provided style
251 if td_styles:
252 if isinstance(td_styles, string_types):
253 return td_styles
254 elif callable(td_styles):
255 return td_styles(v)
256 elif isinstance(td_styles, dict):
257 if h in td_styles:
258 s = td_styles[h]
259 if isinstance(s, string_types):
260 return s
261 elif callable(s):
262 return s(v)
263 else:
264 raise ArgumentError('expected string or callable, got %r'
265 % s)
266 else:
267 raise ArgumentError('expected string, callable or dict, got %r'
268 % td_styles)
269 # fall back to default style
270 if isinstance(v, numeric_types) and not isinstance(v, bool):
271 return 'text-align: right'
272 else:
273 return ''
274
275
276 def _write_end(f, lineterminator):
277 f.write('</tbody>' + lineterminator)
278 f.write('</table>' + lineterminator)