author | Laure Bourgois <Laure.Bourgois@logilab.fr> |
Tue, 02 Dec 2008 10:23:11 +0100 | |
changeset 164 | 031b97433e84 |
parent 159 | ff7b0f8dcb3c |
child 165 | c5ff97312b8a |
permissions | -rw-r--r-- |
0 | 1 |
# -*- coding: utf-8 -*- |
2 |
"""user interface libraries |
|
3 |
||
4 |
contains some functions designed to help implementation of cubicweb user interface |
|
5 |
||
6 |
:organization: Logilab |
|
7 |
:copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
|
8 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
|
9 |
""" |
|
10 |
__docformat__ = "restructuredtext en" |
|
11 |
||
12 |
import csv |
|
13 |
import decimal |
|
14 |
import locale |
|
15 |
import re |
|
16 |
from urllib import quote as urlquote |
|
17 |
from cStringIO import StringIO |
|
18 |
from xml.parsers.expat import ExpatError |
|
164 | 19 |
from lxml import etree |
20 |
from copy import deepcopy |
|
0 | 21 |
|
22 |
import simplejson |
|
23 |
||
24 |
from mx.DateTime import DateTimeType, DateTimeDeltaType |
|
25 |
||
26 |
from logilab.common.textutils import unormalize |
|
27 |
||
28 |
def ustrftime(date, fmt='%Y-%m-%d'): |
|
29 |
"""like strftime, but returns a unicode string instead of an encoded |
|
30 |
string which may be problematic with localized date. |
|
31 |
|
|
32 |
encoding is guessed by locale.getpreferredencoding() |
|
33 |
""" |
|
34 |
# date format may depend on the locale |
|
35 |
encoding = locale.getpreferredencoding(do_setlocale=False) or 'UTF-8' |
|
36 |
return unicode(date.strftime(fmt), encoding) |
|
37 |
||
38 |
||
39 |
def rql_for_eid(eid): |
|
40 |
"""return the rql query necessary to fetch entity with the given eid. This |
|
41 |
function should only be used to generate link with rql inside, not to give |
|
42 |
to cursor.execute (in which case you won't benefit from rql cache). |
|
43 |
||
44 |
:Parameters: |
|
45 |
- `eid`: the eid of the entity we should search |
|
46 |
:rtype: str |
|
47 |
:return: the rql query |
|
48 |
""" |
|
49 |
return 'Any X WHERE X eid %s' % eid |
|
50 |
||
51 |
||
52 |
def printable_value(req, attrtype, value, props=None, displaytime=True): |
|
53 |
"""return a displayable value (i.e. unicode string)""" |
|
54 |
if value is None or attrtype == 'Bytes': |
|
55 |
return u'' |
|
56 |
if attrtype == 'String': |
|
57 |
# don't translate empty value if you don't want strange results |
|
58 |
if props is not None and value and props.get('internationalizable'): |
|
59 |
return req._(value) |
|
60 |
||
61 |
return value |
|
62 |
if attrtype == 'Date': |
|
63 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
64 |
if attrtype == 'Time': |
|
65 |
return ustrftime(value, req.property_value('ui.time-format')) |
|
66 |
if attrtype == 'Datetime': |
|
67 |
if not displaytime: |
|
68 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
69 |
return ustrftime(value, req.property_value('ui.datetime-format')) |
|
70 |
if attrtype == 'Boolean': |
|
71 |
if value: |
|
72 |
return req._('yes') |
|
73 |
return req._('no') |
|
74 |
if attrtype == 'Float': |
|
75 |
value = req.property_value('ui.float-format') % value |
|
76 |
return unicode(value) |
|
77 |
||
78 |
||
79 |
# text publishing ############################################################# |
|
80 |
||
81 |
try: |
|
82 |
from cubicweb.common.rest import rest_publish # pylint: disable-msg=W0611 |
|
83 |
except ImportError: |
|
84 |
def rest_publish(entity, data): |
|
85 |
"""default behaviour if docutils was not found""" |
|
86 |
return data |
|
87 |
||
88 |
TAG_PROG = re.compile(r'</?.*?>', re.U) |
|
89 |
def remove_html_tags(text): |
|
90 |
"""Removes HTML tags from text |
|
91 |
||
92 |
>>> remove_html_tags('<td>hi <a href="http://www.google.fr">world</a></td>') |
|
93 |
'hi world' |
|
94 |
>>> |
|
95 |
""" |
|
96 |
return TAG_PROG.sub('', text) |
|
97 |
||
98 |
||
99 |
REF_PROG = re.compile(r"<ref\s+rql=([\'\"])([^\1]*?)\1\s*>([^<]*)</ref>", re.U) |
|
100 |
def _subst_rql(view, obj): |
|
101 |
delim, rql, descr = obj.groups() |
|
102 |
return u'<a href="%s">%s</a>' % (view.build_url(rql=rql), descr) |
|
103 |
||
104 |
def html_publish(view, text): |
|
105 |
"""replace <ref rql=''> links by <a href="...">""" |
|
106 |
if not text: |
|
107 |
return u'' |
|
108 |
return REF_PROG.sub(lambda obj, view=view:_subst_rql(view, obj), text) |
|
109 |
||
110 |
try: |
|
111 |
from lxml import etree |
|
112 |
except ImportError: |
|
113 |
# gae environment: lxml not availabel |
|
114 |
||
115 |
def soup2xhtml(data, encoding): |
|
116 |
return data |
|
117 |
||
118 |
else: |
|
119 |
||
120 |
def soup2xhtml(data, encoding): |
|
121 |
"""tidy (at least try) html soup and return the result |
|
122 |
Note: the function considers a string with no surrounding tag as valid |
|
123 |
if <div>`data`</div> can be parsed by an XML parser |
|
124 |
""" |
|
125 |
xmltree = etree.HTML('<div>%s</div>' % data) |
|
126 |
# NOTE: lxml 1.1 (etch platforms) doesn't recognize |
|
127 |
# the encoding=unicode parameter (lxml 2.0 does), this is |
|
128 |
# why we specify an encoding and re-decode to unicode later |
|
129 |
body = etree.tostring(xmltree[0], encoding=encoding) |
|
130 |
# remove <body> and </body> and decode to unicode |
|
131 |
return body[11:-13].decode(encoding) |
|
132 |
||
133 |
||
134 |
# HTML generation helper functions ############################################ |
|
135 |
||
136 |
from logilab.mtconverter import html_escape |
|
137 |
||
138 |
def tooltipize(text, tooltip, url=None): |
|
139 |
"""make an HTML tooltip""" |
|
140 |
url = url or '#' |
|
141 |
return u'<a href="%s" title="%s">%s</a>' % (url, tooltip, text) |
|
142 |
||
143 |
def toggle_action(nodeid): |
|
144 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
145 |
return u"javascript: toggleVisibility('%s')" % nodeid |
|
146 |
||
147 |
def toggle_link(nodeid, label): |
|
148 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
149 |
return u'<a href="%s">%s</a>' % (toggle_action(nodeid), label) |
|
150 |
||
151 |
def ajax_replace_url(nodeid, rql, vid=None, swap=False, **extraparams): |
|
152 |
"""builds a replacePageChunk-like url |
|
153 |
>>> ajax_replace_url('foo', 'Person P') |
|
154 |
"javascript: replacePageChunk('foo', 'Person%20P');" |
|
155 |
>>> ajax_replace_url('foo', 'Person P', 'oneline') |
|
156 |
"javascript: replacePageChunk('foo', 'Person%20P', 'oneline');" |
|
157 |
>>> ajax_replace_url('foo', 'Person P', 'oneline', name='bar', age=12) |
|
158 |
"javascript: replacePageChunk('foo', 'Person%20P', 'oneline', {'age':12, 'name':'bar'});" |
|
159 |
>>> ajax_replace_url('foo', 'Person P', name='bar', age=12) |
|
160 |
"javascript: replacePageChunk('foo', 'Person%20P', 'null', {'age':12, 'name':'bar'});" |
|
161 |
""" |
|
162 |
params = [repr(nodeid), repr(urlquote(rql))] |
|
163 |
if extraparams and not vid: |
|
164 |
params.append("'null'") |
|
165 |
elif vid: |
|
166 |
params.append(repr(vid)) |
|
167 |
if extraparams: |
|
168 |
params.append(simplejson.dumps(extraparams)) |
|
169 |
if swap: |
|
170 |
params.append('true') |
|
171 |
return "javascript: replacePageChunk(%s);" % ', '.join(params) |
|
172 |
||
173 |
def safe_cut(text, length): |
|
174 |
"""returns a string of length <length> based on <text>, removing any html |
|
175 |
tags from given text if cut is necessary. |
|
176 |
""" |
|
177 |
if text is None: |
|
178 |
return u'' |
|
159
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
179 |
textParse = etree.HTML(text) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
180 |
compteur = 0 |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
181 |
|
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
182 |
for element in textParse.iter(): |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
183 |
if compteur > length: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
184 |
parent = element.getparent() |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
185 |
parent.remove(element) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
186 |
else: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
187 |
if element.text is not None: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
188 |
text_resum = text_cut_letters(element.text,length) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
189 |
len_text_resum = len(''.join(text_resum.split())) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
190 |
compteur = compteur + len_text_resum |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
191 |
element.text = text_resum |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
192 |
|
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
193 |
if element.tail is not None: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
194 |
if compteur < length: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
195 |
text_resum = text_cut_letters(element.tail,length) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
196 |
len_text_resum = len(''.join(text_resum.split())) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
197 |
compteur = compteur + len_text_resum |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
198 |
element.tail = text_resum |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
199 |
else: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
200 |
element.tail = '' |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
201 |
|
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
202 |
div = etree.HTML('<div></div>')[0][0] |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
203 |
listNode = textParse[0].getchildren() |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
204 |
for node in listNode: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
205 |
div.append(deepcopy(node)) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
206 |
return etree.tounicode(div) |
0 | 207 |
|
208 |
def text_cut(text, nbwords=30): |
|
209 |
if text is None: |
|
210 |
return u'' |
|
211 |
minlength = len(' '.join(text.split()[:nbwords])) |
|
212 |
textlength = text.find('.', minlength) + 1 |
|
213 |
if textlength == 0: # no point found |
|
214 |
textlength = minlength |
|
215 |
return text[:textlength] |
|
216 |
||
159
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
217 |
def text_cut_letters(text, nbletters): |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
218 |
if text is None: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
219 |
return u'' |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
220 |
if len(''.join(text.split())) <= nbletters: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
221 |
return text |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
222 |
else: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
223 |
text_nospace = ''.join(text.split()) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
224 |
textlength=text.find('.') + 1 |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
225 |
|
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
226 |
if textlength==0: |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
227 |
textlength=text.find(' ', nbletters+5) |
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
228 |
|
ff7b0f8dcb3c
safe_cut fonction return a resum from html text.
Laure Bourgois <Laure.Bourgois@logilab.fr>
parents:
0
diff
changeset
|
229 |
return text[:textlength] |
0 | 230 |
|
231 |
def cut(text, length): |
|
232 |
"""returns a string of length <length> based on <text> |
|
233 |
post: |
|
234 |
len(__return__) <= length |
|
235 |
""" |
|
236 |
if text is None: |
|
237 |
return u'' |
|
238 |
if len(text) <= length: |
|
239 |
return text |
|
240 |
# else if un-tagged text is too long, cut it |
|
241 |
return text[:length-3] + u'...' |
|
242 |
||
243 |
||
244 |
from StringIO import StringIO |
|
245 |
||
246 |
def ureport_as_html(layout): |
|
247 |
from logilab.common.ureports import HTMLWriter |
|
248 |
formater = HTMLWriter(True) |
|
249 |
stream = StringIO() #UStringIO() don't want unicode assertion |
|
250 |
formater.format(layout, stream) |
|
251 |
res = stream.getvalue() |
|
252 |
if isinstance(res, str): |
|
253 |
res = unicode(res, 'UTF8') |
|
254 |
return res |
|
255 |
||
256 |
def render_HTML_tree(tree, selected_node=None, render_node=None, caption=None): |
|
257 |
""" |
|
258 |
Generate a pure HTML representation of a tree given as an instance |
|
259 |
of a logilab.common.tree.Node |
|
260 |
||
261 |
selected_node is the currently selected node (if any) which will |
|
262 |
have its surrounding <div> have id="selected" (which default |
|
263 |
to a bold border libe with the default CSS). |
|
264 |
||
265 |
render_node is a function that should take a Node content (Node.id) |
|
266 |
as parameter and should return a string (what will be displayed |
|
267 |
in the cell). |
|
268 |
||
269 |
Warning: proper rendering of the generated html code depends on html_tree.css |
|
270 |
""" |
|
271 |
tree_depth = tree.depth_down() |
|
272 |
if render_node is None: |
|
273 |
render_node = str |
|
274 |
||
275 |
# helper function that build a matrix from the tree, like: |
|
276 |
# +------+-----------+-----------+ |
|
277 |
# | root | child_1_1 | child_2_1 | |
|
278 |
# | root | child_1_1 | child_2_2 | |
|
279 |
# | root | child_1_2 | | |
|
280 |
# | root | child_1_3 | child_2_3 | |
|
281 |
# | root | child_1_3 | child_2_4 | |
|
282 |
# +------+-----------+-----------+ |
|
283 |
# from: |
|
284 |
# root -+- child_1_1 -+- child_2_1 |
|
285 |
# | | |
|
286 |
# | +- child_2_2 |
|
287 |
# +- child_1_2 |
|
288 |
# | |
|
289 |
# +- child1_3 -+- child_2_3 |
|
290 |
# | |
|
291 |
# +- child_2_2 |
|
292 |
def build_matrix(path, matrix): |
|
293 |
if path[-1].is_leaf(): |
|
294 |
matrix.append(path[:]) |
|
295 |
else: |
|
296 |
for child in path[-1].children: |
|
297 |
build_matrix(path[:] + [child], matrix) |
|
298 |
||
299 |
matrix = [] |
|
300 |
build_matrix([tree], matrix) |
|
301 |
||
302 |
# make all lines in the matrix have the same number of columns |
|
303 |
for line in matrix: |
|
304 |
line.extend([None]*(tree_depth-len(line))) |
|
305 |
for i in range(len(matrix)-1, 0, -1): |
|
306 |
prev_line, line = matrix[i-1:i+1] |
|
307 |
for j in range(len(line)): |
|
308 |
if line[j] == prev_line[j]: |
|
309 |
line[j] = None |
|
310 |
||
311 |
# We build the matrix of link types (between 2 cells on a line of the matrix) |
|
312 |
# link types are : |
|
313 |
link_types = {(True, True, True ): 1, # T |
|
314 |
(False, False, True ): 2, # | |
|
315 |
(False, True, True ): 3, # + (actually, vert. bar with horiz. bar on the right) |
|
316 |
(False, True, False): 4, # L |
|
317 |
(True, True, False): 5, # - |
|
318 |
} |
|
319 |
links = [] |
|
320 |
for i, line in enumerate(matrix): |
|
321 |
links.append([]) |
|
322 |
for j in range(tree_depth-1): |
|
323 |
cell_11 = line[j] is not None |
|
324 |
cell_12 = line[j+1] is not None |
|
325 |
cell_21 = line[j+1] is not None and line[j+1].next_sibling() is not None |
|
326 |
link_type = link_types.get((cell_11, cell_12, cell_21), 0) |
|
327 |
if link_type == 0 and i > 0 and links[i-1][j] in (1,2,3): |
|
328 |
link_type = 2 |
|
329 |
links[-1].append(link_type) |
|
330 |
||
331 |
||
332 |
# We can now generate the HTML code for the <table> |
|
333 |
s = u'<table class="tree">\n' |
|
334 |
if caption: |
|
335 |
s += '<caption>%s</caption>\n' % caption |
|
336 |
||
337 |
for i, link_line in enumerate(links): |
|
338 |
line = matrix[i] |
|
339 |
||
340 |
s += '<tr>' |
|
341 |
for j, link_cell in enumerate(link_line): |
|
342 |
cell = line[j] |
|
343 |
if cell: |
|
344 |
if cell.id == selected_node: |
|
345 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
346 |
else: |
|
347 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
348 |
else: |
|
349 |
s += '<td rowspan="2"> </td>' |
|
350 |
s += '<td class="tree_cell_%d_1"> </td>' % link_cell |
|
351 |
s += '<td class="tree_cell_%d_2"> </td>' % link_cell |
|
352 |
||
353 |
cell = line[-1] |
|
354 |
if cell: |
|
355 |
if cell.id == selected_node: |
|
356 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
357 |
else: |
|
358 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
359 |
else: |
|
360 |
s += '<td rowspan="2"> </td>' |
|
361 |
||
362 |
s += '</tr>\n' |
|
363 |
if link_line: |
|
364 |
s += '<tr>' |
|
365 |
for j, link_cell in enumerate(link_line): |
|
366 |
s += '<td class="tree_cell_%d_3"> </td>' % link_cell |
|
367 |
s += '<td class="tree_cell_%d_4"> </td>' % link_cell |
|
368 |
s += '</tr>\n' |
|
369 |
||
370 |
s += '</table>' |
|
371 |
return s |
|
372 |
||
373 |
||
374 |
||
375 |
# traceback formatting ######################################################## |
|
376 |
||
377 |
import traceback |
|
378 |
||
379 |
def rest_traceback(info, exception): |
|
380 |
"""return a ReST formated traceback""" |
|
381 |
res = [u'Traceback\n---------\n::\n'] |
|
382 |
for stackentry in traceback.extract_tb(info[2]): |
|
383 |
res.append(u'\tFile %s, line %s, function %s' % tuple(stackentry[:3])) |
|
384 |
if stackentry[3]: |
|
385 |
res.append(u'\t %s' % stackentry[3].decode('utf-8', 'replace')) |
|
386 |
res.append(u'\n') |
|
387 |
try: |
|
388 |
res.append(u'\t Error: %s\n' % exception) |
|
389 |
except: |
|
390 |
pass |
|
391 |
return u'\n'.join(res) |
|
392 |
||
393 |
||
394 |
def html_traceback(info, exception, title='', |
|
395 |
encoding='ISO-8859-1', body=''): |
|
396 |
""" return an html formatted traceback from python exception infos. |
|
397 |
""" |
|
398 |
tcbk = info[2] |
|
399 |
stacktb = traceback.extract_tb(tcbk) |
|
400 |
strings = [] |
|
401 |
if body: |
|
402 |
strings.append(u'<div class="error_body">') |
|
403 |
# FIXME |
|
404 |
strings.append(body) |
|
405 |
strings.append(u'</div>') |
|
406 |
if title: |
|
407 |
strings.append(u'<h1 class="error">%s</h1>'% html_escape(title)) |
|
408 |
try: |
|
409 |
strings.append(u'<p class="error">%s</p>' % html_escape(str(exception)).replace("\n","<br />")) |
|
410 |
except UnicodeError: |
|
411 |
pass |
|
412 |
strings.append(u'<div class="error_traceback">') |
|
413 |
for index, stackentry in enumerate(stacktb): |
|
414 |
strings.append(u'<b>File</b> <b class="file">%s</b>, <b>line</b> ' |
|
415 |
u'<b class="line">%s</b>, <b>function</b> ' |
|
416 |
u'<b class="function">%s</b>:<br/>'%( |
|
417 |
html_escape(stackentry[0]), stackentry[1], html_escape(stackentry[2]))) |
|
418 |
if stackentry[3]: |
|
419 |
string = html_escape(stackentry[3]).decode('utf-8', 'replace') |
|
420 |
strings.append(u' %s<br/>\n' % (string)) |
|
421 |
# add locals info for each entry |
|
422 |
try: |
|
423 |
local_context = tcbk.tb_frame.f_locals |
|
424 |
html_info = [] |
|
425 |
chars = 0 |
|
426 |
for name, value in local_context.iteritems(): |
|
427 |
value = html_escape(repr(value)) |
|
428 |
info = u'<span class="name">%s</span>=%s, ' % (name, value) |
|
429 |
line_length = len(name) + len(value) |
|
430 |
chars += line_length |
|
431 |
# 150 is the result of *years* of research ;-) (CSS might be helpful here) |
|
432 |
if chars > 150: |
|
433 |
info = u'<br/>' + info |
|
434 |
chars = line_length |
|
435 |
html_info.append(info) |
|
436 |
boxid = 'ctxlevel%d' % index |
|
437 |
strings.append(u'[%s]' % toggle_link(boxid, '+')) |
|
438 |
strings.append(u'<div id="%s" class="pycontext hidden">%s</div>' % |
|
439 |
(boxid, ''.join(html_info))) |
|
440 |
tcbk = tcbk.tb_next |
|
441 |
except Exception: |
|
442 |
pass # doesn't really matter if we have no context info |
|
443 |
strings.append(u'</div>') |
|
444 |
return '\n'.join(strings) |
|
445 |
||
446 |
# csv files / unicode support ################################################# |
|
447 |
||
448 |
class UnicodeCSVWriter: |
|
449 |
"""proxies calls to csv.writer.writerow to be able to deal with unicode""" |
|
450 |
||
451 |
def __init__(self, wfunc, encoding, **kwargs): |
|
452 |
self.writer = csv.writer(self, **kwargs) |
|
453 |
self.wfunc = wfunc |
|
454 |
self.encoding = encoding |
|
455 |
||
456 |
def write(self, data): |
|
457 |
self.wfunc(data) |
|
458 |
||
459 |
def writerow(self, row): |
|
460 |
csvrow = [] |
|
461 |
for elt in row: |
|
462 |
if isinstance(elt, unicode): |
|
463 |
csvrow.append(elt.encode(self.encoding)) |
|
464 |
else: |
|
465 |
csvrow.append(str(elt)) |
|
466 |
self.writer.writerow(csvrow) |
|
467 |
||
468 |
def writerows(self, rows): |
|
469 |
for row in rows: |
|
470 |
self.writerow(row) |
|
471 |
||
472 |
||
473 |
# some decorators ############################################################# |
|
474 |
||
475 |
class limitsize(object): |
|
476 |
def __init__(self, maxsize): |
|
477 |
self.maxsize = maxsize |
|
478 |
||
479 |
def __call__(self, function): |
|
480 |
def newfunc(*args, **kwargs): |
|
481 |
ret = function(*args, **kwargs) |
|
482 |
if isinstance(ret, basestring): |
|
483 |
return ret[:self.maxsize] |
|
484 |
return ret |
|
485 |
return newfunc |
|
486 |
||
487 |
||
488 |
def jsonize(function): |
|
489 |
import simplejson |
|
490 |
def newfunc(*args, **kwargs): |
|
491 |
ret = function(*args, **kwargs) |
|
492 |
if isinstance(ret, decimal.Decimal): |
|
493 |
ret = float(ret) |
|
494 |
elif isinstance(ret, DateTimeType): |
|
495 |
ret = ret.strftime('%Y-%m-%d %H:%M') |
|
496 |
elif isinstance(ret, DateTimeDeltaType): |
|
497 |
ret = ret.seconds |
|
498 |
try: |
|
499 |
return simplejson.dumps(ret) |
|
500 |
except TypeError: |
|
501 |
return simplejson.dumps(repr(ret)) |
|
502 |
return newfunc |
|
503 |
||
504 |
||
505 |
def htmlescape(function): |
|
506 |
def newfunc(*args, **kwargs): |
|
507 |
ret = function(*args, **kwargs) |
|
508 |
assert isinstance(ret, basestring) |
|
509 |
return html_escape(ret) |
|
510 |
return newfunc |