Mercurial > cpython-lru_cache-weakref
annotate Lib/cgitb.py @ 24042:63fbbed10714 legacy-trunk
Simplify HTTPSConnection constructor.
See discussion in SF bug 458463.
| author | Jeremy Hylton <jeremy@alum.mit.edu> |
|---|---|
| date | Fri, 28 Jun 2002 23:38:14 +0000 |
| parents | dab8701bd3fa |
| children | 11c701038805 |
| rev | line source |
|---|---|
| 19365 | 1 """Handle exceptions in CGI scripts by formatting tracebacks into nice HTML. |
| 2 | |
| 3 To enable this module, do: | |
| 4 | |
| 5 import cgitb; cgitb.enable() | |
| 6 | |
| 7 at the top of your CGI script. The optional arguments to enable() are: | |
| 8 | |
| 9 display - if true, tracebacks are displayed in the web browser | |
| 10 logdir - if set, tracebacks are written to files in this directory | |
| 19421 | 11 context - number of lines of source code to show for each stack frame |
| 19365 | 12 |
| 19421 | 13 By default, tracebacks are displayed but not saved, and context is 5. |
| 19365 | 14 |
| 15 Alternatively, if you have caught an exception and want cgitb to display it | |
|
21480
21c7d7565977
Make the module docstring agree with reality: the module prvides the
Fred Drake <fdrake@acm.org>
parents:
21194
diff
changeset
|
16 for you, call cgitb.handler(). The optional argument to handler() is a 3-item |
| 19365 | 17 tuple (etype, evalue, etb) just like the value of sys.exc_info().""" |
| 18 | |
| 19 __author__ = 'Ka-Ping Yee' | |
| 20 __version__ = '$Revision$' | |
| 21 | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
22 import sys |
|
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
23 |
| 19365 | 24 def reset(): |
| 25 """Return a string that resets the CGI and browser to a known state.""" | |
| 26 return '''<!--: spam | |
| 27 Content-Type: text/html | |
| 28 | |
| 19421 | 29 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> |
| 30 <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --> | |
| 19365 | 31 </font> </font> </font> </script> </object> </blockquote> </pre> |
| 32 </table> </table> </table> </table> </table> </font> </font> </font>''' | |
| 33 | |
| 19421 | 34 __UNDEF__ = [] # a special sentinel object |
| 35 def small(text): return '<small>' + text + '</small>' | |
| 36 def strong(text): return '<strong>' + text + '</strong>' | |
| 37 def grey(text): return '<font color="#909090">' + text + '</font>' | |
| 38 | |
| 39 def lookup(name, frame, locals): | |
| 40 """Find the value for a given name in the given environment.""" | |
| 41 if name in locals: | |
| 42 return 'local', locals[name] | |
| 43 if name in frame.f_globals: | |
| 44 return 'global', frame.f_globals[name] | |
|
23998
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
45 if '__builtins__' in frame.f_globals: |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
46 builtins = frame.f_globals['__builtins__'] |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
47 if type(builtins) is type({}): |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
48 if name in builtins: |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
49 return 'builtin', builtins[name] |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
50 else: |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
51 if hasattr(builtins, name): |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
52 return 'builtin', getattr(builtins, name) |
| 19421 | 53 return None, __UNDEF__ |
| 54 | |
| 55 def scanvars(reader, frame, locals): | |
| 56 """Scan one logical line of Python and look up values of variables used.""" | |
| 57 import tokenize, keyword | |
| 58 vars, lasttoken, parent, prefix = [], None, None, '' | |
| 59 for ttype, token, start, end, line in tokenize.generate_tokens(reader): | |
| 60 if ttype == tokenize.NEWLINE: break | |
| 61 if ttype == tokenize.NAME and token not in keyword.kwlist: | |
| 62 if lasttoken == '.': | |
| 63 if parent is not __UNDEF__: | |
| 64 value = getattr(parent, token, __UNDEF__) | |
| 65 vars.append((prefix + token, prefix, value)) | |
| 66 else: | |
| 67 where, value = lookup(token, frame, locals) | |
| 68 vars.append((token, where, value)) | |
| 69 elif token == '.': | |
| 70 prefix += lasttoken + '.' | |
| 71 parent = value | |
| 72 else: | |
| 73 parent, prefix = None, '' | |
| 74 lasttoken = token | |
| 75 return vars | |
| 76 | |
| 77 def html((etype, evalue, etb), context=5): | |
| 78 """Return a nice HTML document describing a given traceback.""" | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
79 import os, types, time, traceback, linecache, inspect, pydoc |
| 19365 | 80 |
| 81 if type(etype) is types.ClassType: | |
| 82 etype = etype.__name__ | |
| 83 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable | |
| 84 date = time.ctime(time.time()) | |
| 19421 | 85 head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading( |
| 19365 | 86 '<big><big><strong>%s</strong></big></big>' % str(etype), |
| 19421 | 87 '#ffffff', '#6622aa', pyver + '<br>' + date) + ''' |
| 88 <p>A problem occurred in a Python script. Here is the sequence of | |
| 89 function calls leading up to the error, in the order they occurred.''' | |
| 19365 | 90 |
| 19421 | 91 indent = '<tt>' + small(' ' * 5) + ' </tt>' |
| 19365 | 92 frames = [] |
| 93 records = inspect.getinnerframes(etb, context) | |
| 94 for frame, file, lnum, func, lines, index in records: | |
| 95 file = file and os.path.abspath(file) or '?' | |
| 19421 | 96 link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file)) |
| 19365 | 97 args, varargs, varkw, locals = inspect.getargvalues(frame) |
| 19421 | 98 call = '' |
| 99 if func != '?': | |
| 100 call = 'in ' + strong(func) + \ | |
| 101 inspect.formatargvalues(args, varargs, varkw, locals, | |
| 102 formatvalue=lambda value: '=' + pydoc.html.repr(value)) | |
| 19365 | 103 |
| 19421 | 104 highlight = {} |
| 105 def reader(lnum=[lnum]): | |
| 106 highlight[lnum[0]] = 1 | |
| 107 try: return linecache.getline(file, lnum[0]) | |
| 108 finally: lnum[0] += 1 | |
| 109 vars = scanvars(reader, frame, locals) | |
| 19365 | 110 |
| 19421 | 111 rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' % |
| 112 ('<big> </big>', link, call)] | |
| 19365 | 113 if index is not None: |
| 114 i = lnum - index | |
| 115 for line in lines: | |
| 19421 | 116 num = small(' ' * (5-len(str(i))) + str(i)) + ' ' |
| 117 line = '<tt>%s%s</tt>' % (num, pydoc.html.preformat(line)) | |
| 118 if i in highlight: | |
| 119 rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line) | |
| 120 else: | |
| 121 rows.append('<tr><td>%s</td></tr>' % grey(line)) | |
| 122 i += 1 | |
| 19365 | 123 |
| 19421 | 124 done, dump = {}, [] |
| 125 for name, where, value in vars: | |
| 126 if name in done: continue | |
| 127 done[name] = 1 | |
| 128 if value is not __UNDEF__: | |
|
23998
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
129 if where in ['global', 'builtin']: |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
130 name = ('<em>%s</em> ' % where) + strong(name) |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
131 elif where == 'local': |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
132 name = strong(name) |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
133 else: |
|
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
134 name = where + strong(name.split('.')[-1]) |
| 19421 | 135 dump.append('%s = %s' % (name, pydoc.html.repr(value))) |
| 136 else: | |
| 137 dump.append(name + ' <em>undefined</em>') | |
| 138 | |
| 139 rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump)))) | |
| 140 frames.append('''<p> | |
| 141 <table width="100%%" cellspacing=0 cellpadding=0 border=0> | |
| 142 %s</table>''' % '\n'.join(rows)) | |
| 143 | |
| 144 exception = ['<p>%s: %s' % (strong(str(etype)), str(evalue))] | |
| 19365 | 145 if type(evalue) is types.InstanceType: |
| 146 for name in dir(evalue): | |
|
23998
dab8701bd3fa
Also look up variable names in __builtins__ if not found in globals.
Ka-Ping Yee <ping@zesty.ca>
parents:
21480
diff
changeset
|
147 if name[:1] == '_': continue |
| 19365 | 148 value = pydoc.html.repr(getattr(evalue, name)) |
| 149 exception.append('\n<br>%s%s =\n%s' % (indent, name, value)) | |
| 150 | |
| 151 import traceback | |
| 152 return head + ''.join(frames) + ''.join(exception) + ''' | |
| 153 | |
| 154 | |
| 19421 | 155 <!-- The above is a description of an error in a Python program, formatted |
| 156 for a Web browser because the 'cgitb' module was enabled. In case you | |
| 157 are not reading this in a Web browser, here is the original traceback: | |
| 19365 | 158 |
| 159 %s | |
| 160 --> | |
| 19421 | 161 ''' % ''.join(traceback.format_exception(etype, evalue, etb)) |
| 19365 | 162 |
| 163 class Hook: | |
| 19421 | 164 """A hook to replace sys.excepthook that shows tracebacks in HTML.""" |
| 165 | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
166 def __init__(self, display=1, logdir=None, context=5, file=None): |
| 19365 | 167 self.display = display # send tracebacks to browser if true |
| 168 self.logdir = logdir # log tracebacks to files if not None | |
| 19421 | 169 self.context = context # number of source code lines per frame |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
170 self.file = file or sys.stdout # place to send the output |
| 19365 | 171 |
| 172 def __call__(self, etype, evalue, etb): | |
| 173 self.handle((etype, evalue, etb)) | |
| 174 | |
| 175 def handle(self, info=None): | |
| 176 info = info or sys.exc_info() | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
177 self.file.write(reset()) |
| 19365 | 178 |
| 179 try: | |
| 19421 | 180 text, doc = 0, html(info, self.context) |
| 19365 | 181 except: # just in case something goes wrong |
| 182 import traceback | |
| 19421 | 183 text, doc = 1, ''.join(traceback.format_exception(*info)) |
| 19365 | 184 |
| 185 if self.display: | |
| 186 if text: | |
| 187 doc = doc.replace('&', '&').replace('<', '<') | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
188 self.file.write('<pre>' + doc + '</pre>\n') |
| 19365 | 189 else: |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
190 self.file.write(doc + '\n') |
| 19365 | 191 else: |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
192 self.file.write('<p>A problem occurred in a Python script.\n') |
| 19365 | 193 |
| 194 if self.logdir is not None: | |
| 19421 | 195 import os, tempfile |
| 19365 | 196 name = tempfile.mktemp(['.html', '.txt'][text]) |
| 197 path = os.path.join(self.logdir, os.path.basename(name)) | |
| 198 try: | |
| 199 file = open(path, 'w') | |
| 200 file.write(doc) | |
| 201 file.close() | |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
202 msg = '<p> %s contains the description of this error.' % path |
| 19365 | 203 except: |
|
21194
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
204 msg = '<p> Tried to save traceback to %s, but failed.' % path |
|
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
205 self.file.write(msg + '\n') |
|
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
206 try: |
|
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
207 self.file.flush() |
|
1519d6faab15
Add "file" argument to Hook constructor.
Ka-Ping Yee <ping@zesty.ca>
parents:
19421
diff
changeset
|
208 except: pass |
| 19365 | 209 |
| 210 handler = Hook().handle | |
| 19421 | 211 def enable(display=1, logdir=None, context=5): |
| 212 """Install an exception handler that formats tracebacks as HTML. | |
| 213 | |
| 214 The optional argument 'display' can be set to 0 to suppress sending the | |
| 215 traceback to the browser, and 'logdir' can be set to a directory to cause | |
| 216 tracebacks to be written to files there.""" | |
| 217 sys.excepthook = Hook(display, logdir, context) |
