Debian Codegraph @

weblogo/_ext/cgitb.py

raw
1
2 # type: ignore
3
4 # cgithb library imported from python 3.12
5 # Distributed under the PSF license
6 # https://docs.python.org/3/license.html
7
8
9 """More comprehensive traceback formatting for Python scripts.
10
11 To enable this module, do:
12
13 import cgitb; cgitb.enable()
14
15 at the top of your script. The optional arguments to enable() are:
16
17 display - if true, tracebacks are displayed in the web browser
18 logdir - if set, tracebacks are written to files in this directory
19 context - number of lines of source code to show for each stack frame
20 format - 'text' or 'html' controls the output format
21
22 By default, tracebacks are displayed but not saved, the context is 5 lines
23 and the output format is 'html' (for backwards compatibility with the
24 original use of this module)
25
26 Alternatively, if you have caught an exception and want cgitb to display it
27 for you, call cgitb.handler(). The optional argument to handler() is a
28 3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
29 The default handler displays output as HTML.
30
31 """
32
33
34
35 import inspect
36 import keyword
37 import linecache
38 import os
39 import pydoc
40 import sys
41 import tempfile
42 import time
43 import tokenize
44 import traceback
45 import warnings
46 from html import escape as html_escape
47
48 # warnings._deprecated(__name__, remove=(3, 13))
49
50
51 def reset():
52 """Return a string that resets the CGI and browser to a known state."""
53 return """<!--: spam
54 Content-Type: text/html
55
56 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
57 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
58 </font> </font> </font> </script> </object> </blockquote> </pre>
59 </table> </table> </table> </table> </table> </font> </font> </font>"""
60
61
62 __UNDEF__ = [] # a special sentinel object
63
64
65 def small(text):
66 if text:
67 return "<small>" + text + "</small>"
68 else:
69 return ""
70
71
72 def strong(text):
73 if text:
74 return "<strong>" + text + "</strong>"
75 else:
76 return ""
77
78
79 def grey(text):
80 if text:
81 return '<font color="#909090">' + text + "</font>"
82 else:
83 return ""
84
85
86 def lookup(name, frame, locals):
87 """Find the value for a given name in the given environment."""
88 if name in locals:
89 return "local", locals[name]
90 if name in frame.f_globals:
91 return "global", frame.f_globals[name]
92 if "__builtins__" in frame.f_globals:
93 builtins = frame.f_globals["__builtins__"]
94 if isinstance(builtins, dict):
95 if name in builtins:
96 return "builtin", builtins[name]
97 else:
98 if hasattr(builtins, name):
99 return "builtin", getattr(builtins, name)
100 return None, __UNDEF__
101
102
103 def scanvars(reader, frame, locals):
104 """Scan one logical line of Python and look up values of variables used."""
105 vars, lasttoken, parent, prefix, value = [], None, None, "", __UNDEF__
106 for ttype, token, start, end, line in tokenize.generate_tokens(reader):
107 if ttype == tokenize.NEWLINE:
108 break
109 if ttype == tokenize.NAME and token not in keyword.kwlist:
110 if lasttoken == ".":
111 if parent is not __UNDEF__:
112 value = getattr(parent, token, __UNDEF__)
113 vars.append((prefix + token, prefix, value))
114 else:
115 where, value = lookup(token, frame, locals)
116 vars.append((token, where, value))
117 elif token == ".":
118 prefix += lasttoken + "."
119 parent = value
120 else:
121 parent, prefix = None, ""
122 lasttoken = token
123 return vars
124
125
126 def html(einfo, context=5):
127 """Return a nice HTML document describing a given traceback."""
128 etype, evalue, etb = einfo
129 if isinstance(etype, type):
130 etype = etype.__name__
131 pyver = "Python " + sys.version.split()[0] + ": " + sys.executable
132 date = time.ctime(time.time())
133 head = f"""
134 <body bgcolor="#f0f0f8">
135 <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
136 <tr bgcolor="#6622aa">
137 <td valign=bottom>&nbsp;<br>
138 <font color="#ffffff" face="helvetica, arial">&nbsp;<br>
139 <big><big><strong>{html_escape(str(etype))}</strong></big></big></font></td>
140 <td align=right valign=bottom>
141 <font color="#ffffff" face="helvetica, arial">{pyver}<br>{date}</font></td>
142 </tr></table>
143 <p>A problem occurred in a Python script. Here is the sequence of
144 function calls leading up to the error, in the order they occurred.</p>"""
145
146 indent = "<tt>" + small("&nbsp;" * 5) + "&nbsp;</tt>"
147 frames = []
148 records = inspect.getinnerframes(etb, context)
149 for frame, file, lnum, func, lines, index in records:
150 if file:
151 file = os.path.abspath(file)
152 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
153 else:
154 file = link = "?"
155 args, varargs, varkw, locals = inspect.getargvalues(frame)
156 call = ""
157 if func != "?":
158 call = "in " + strong(pydoc.html.escape(func))
159 if func != "<module>":
160 call += inspect.formatargvalues(
161 args,
162 varargs,
163 varkw,
164 locals,
165 formatvalue=lambda value: "=" + pydoc.html.repr(value),
166 )
167
168 highlight = {}
169
170 def reader(lnum=[lnum]):
171 highlight[lnum[0]] = 1
172 try:
173 return linecache.getline(file, lnum[0])
174 finally:
175 lnum[0] += 1
176
177 vars = scanvars(reader, frame, locals)
178
179 rows = [
180 '<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>'
181 % ("<big>&nbsp;</big>", link, call)
182 ]
183 if index is not None:
184 i = lnum - index
185 for line in lines:
186 num = small("&nbsp;" * (5 - len(str(i))) + str(i)) + "&nbsp;"
187 if i in highlight:
188 line = "<tt>=&gt;%s%s</tt>" % (num, pydoc.html.preformat(line))
189 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
190 else:
191 line = "<tt>&nbsp;&nbsp;%s%s</tt>" % (
192 num,
193 pydoc.html.preformat(line),
194 )
195 rows.append("<tr><td>%s</td></tr>" % grey(line))
196 i += 1
197
198 done, dump = {}, []
199 for name, where, value in vars:
200 if name in done:
201 continue
202 done[name] = 1
203 if value is not __UNDEF__:
204 if where in ("global", "builtin"):
205 name = ("<em>%s</em> " % where) + strong(name)
206 elif where == "local":
207 name = strong(name)
208 else:
209 name = where + strong(name.split(".")[-1])
210 dump.append("%s&nbsp;= %s" % (name, pydoc.html.repr(value)))
211 else:
212 dump.append(name + " <em>undefined</em>")
213
214 rows.append("<tr><td>%s</td></tr>" % small(grey(", ".join(dump))))
215 frames.append(
216 """
217 <table width="100%%" cellspacing=0 cellpadding=0 border=0>
218 %s</table>"""
219 % "\n".join(rows)
220 )
221
222 exception = [
223 "<p>%s: %s"
224 % (strong(pydoc.html.escape(str(etype))), pydoc.html.escape(str(evalue)))
225 ]
226 for name in dir(evalue):
227 if name[:1] == "_":
228 continue
229 value = pydoc.html.repr(getattr(evalue, name))
230 exception.append("\n<br>%s%s&nbsp;=\n%s" % (indent, name, value))
231
232 return (
233 head
234 + "".join(frames)
235 + "".join(exception)
236 + """
237
238
239 <!-- The above is a description of an error in a Python program, formatted
240 for a web browser because the 'cgitb' module was enabled. In case you
241 are not reading this in a web browser, here is the original traceback:
242
243 %s
244 -->
245 """
246 % pydoc.html.escape("".join(traceback.format_exception(etype, evalue, etb)))
247 )
248
249
250 def text(einfo, context=5):
251 """Return a plain text document describing a given traceback."""
252 etype, evalue, etb = einfo
253 if isinstance(etype, type):
254 etype = etype.__name__
255 pyver = "Python " + sys.version.split()[0] + ": " + sys.executable
256 date = time.ctime(time.time())
257 head = (
258 "%s\n%s\n%s\n" % (str(etype), pyver, date)
259 + """
260 A problem occurred in a Python script. Here is the sequence of
261 function calls leading up to the error, in the order they occurred.
262 """
263 )
264
265 frames = []
266 records = inspect.getinnerframes(etb, context)
267 for frame, file, lnum, func, lines, index in records:
268 file = file and os.path.abspath(file) or "?"
269 args, varargs, varkw, locals = inspect.getargvalues(frame)
270 call = ""
271 if func != "?":
272 call = "in " + func
273 if func != "<module>":
274 call += inspect.formatargvalues(
275 args,
276 varargs,
277 varkw,
278 locals,
279 formatvalue=lambda value: "=" + pydoc.text.repr(value),
280 )
281
282 highlight = {}
283
284 def reader(lnum=[lnum]):
285 highlight[lnum[0]] = 1
286 try:
287 return linecache.getline(file, lnum[0])
288 finally:
289 lnum[0] += 1
290
291 vars = scanvars(reader, frame, locals)
292
293 rows = [" %s %s" % (file, call)]
294 if index is not None:
295 i = lnum - index
296 for line in lines:
297 num = "%5d " % i
298 rows.append(num + line.rstrip())
299 i += 1
300
301 done, dump = {}, []
302 for name, where, value in vars:
303 if name in done:
304 continue
305 done[name] = 1
306 if value is not __UNDEF__:
307 if where == "global":
308 name = "global " + name
309 elif where != "local":
310 name = where + name.split(".")[-1]
311 dump.append("%s = %s" % (name, pydoc.text.repr(value)))
312 else:
313 dump.append(name + " undefined")
314
315 rows.append("\n".join(dump))
316 frames.append("\n%s\n" % "\n".join(rows))
317
318 exception = ["%s: %s" % (str(etype), str(evalue))]
319 for name in dir(evalue):
320 value = pydoc.text.repr(getattr(evalue, name))
321 exception.append("\n%s%s = %s" % (" " * 4, name, value))
322
323 return (
324 head
325 + "".join(frames)
326 + "".join(exception)
327 + """
328
329 The above is a description of an error in a Python program. Here is
330 the original traceback:
331
332 %s
333 """
334 % "".join(traceback.format_exception(etype, evalue, etb))
335 )
336
337
338 class Hook:
339 """A hook to replace sys.excepthook that shows tracebacks in HTML."""
340
341 def __init__(self, display=1, logdir=None, context=5, file=None, format="html"):
342 self.display = display # send tracebacks to browser if true
343 self.logdir = logdir # log tracebacks to files if not None
344 self.context = context # number of source code lines per frame
345 self.file = file or sys.stdout # place to send the output
346 self.format = format
347
348 def __call__(self, etype, evalue, etb):
349 self.handle((etype, evalue, etb))
350
351 def handle(self, info=None):
352 info = info or sys.exc_info()
353 if self.format == "html":
354 self.file.write(reset())
355
356 formatter = (self.format == "html") and html or text
357 plain = False
358 try:
359 doc = formatter(info, self.context)
360 except: # just in case something goes wrong
361 doc = "".join(traceback.format_exception(*info))
362 plain = True
363
364 if self.display:
365 if plain:
366 doc = pydoc.html.escape(doc)
367 self.file.write("<pre>" + doc + "</pre>\n")
368 else:
369 self.file.write(doc + "\n")
370 else:
371 self.file.write("<p>A problem occurred in a Python script.\n")
372
373 if self.logdir is not None:
374 suffix = [".txt", ".html"][self.format == "html"]
375 (fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
376
377 try:
378 with os.fdopen(fd, "w") as file:
379 file.write(doc)
380 msg = "%s contains the description of this error." % path
381 except:
382 msg = "Tried to save traceback to %s, but failed." % path
383
384 if self.format == "html":
385 self.file.write("<p>%s</p>\n" % msg)
386 else:
387 self.file.write(msg + "\n")
388 try:
389 self.file.flush()
390 except:
391 pass
392
393
394 handler = Hook().handle
395
396
397 def enable(display=1, logdir=None, context=5, format="html"):
398 """Install an exception handler that formats tracebacks as HTML.
399
400 The optional argument 'display' can be set to 0 to suppress sending the
401 traceback to the browser, and 'logdir' can be set to a directory to cause
402 tracebacks to be written to files there."""
403 sys.excepthook = Hook(
404 display=display, logdir=logdir, context=context, format=format
405 )