"Fossies" - the Fresh Open Source Software Archive

Member "roundup-2.0.0/roundup/cgi/cgitb.py" (29 Jun 2020, 8786 Bytes) of package /linux/www/roundup-2.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "cgitb.py": 1.6.1_vs_2.0.0.

    1 #
    2 # This module was written by Ka-Ping Yee, <ping@lfw.org>.
    3 #
    4 
    5 """Extended CGI traceback handler by Ka-Ping Yee, <ping@lfw.org>.
    6 """
    7 from __future__ import print_function
    8 __docformat__ = 'restructuredtext'
    9 
   10 import sys, os, keyword, linecache, tokenize, inspect
   11 import pydoc, traceback
   12 
   13 from roundup.anypy.html import html_escape
   14 
   15 from roundup.cgi import TranslationService
   16 from roundup.anypy.strings import s2b
   17 
   18 
   19 def get_translator(i18n=None):
   20     """Return message translation function (gettext)
   21 
   22     Parameters:
   23         i18n - translation service, such as roundup.i18n module
   24             or TranslationService object.
   25 
   26     Return ``gettext`` attribute of the ``i18n`` object, if available
   27     (must be a message translation function with one argument).
   28     If ``gettext`` cannot be obtained from ``i18n``, take default
   29     TranslationService.
   30 
   31     """
   32     try:
   33         return i18n.gettext
   34     except AttributeError:
   35         return TranslationService.get_translation().gettext
   36 
   37 
   38 def breaker():
   39     return ('<body bgcolor="white">' +
   40             '<font color="white" size="-5"> > </font> ' +
   41             '</table>' * 5)
   42 
   43 
   44 def niceDict(indent, dict):
   45     l = []
   46     for k in sorted(dict):
   47         v = dict[k]
   48         l.append('<tr><td><strong>%s</strong></td><td>%s</td></tr>' % (k,
   49             html_escape(repr(v))))
   50     return '\n'.join(l)
   51 
   52 
   53 def pt_html(context=5, i18n=None):
   54     _ = get_translator(i18n)
   55     esc = html_escape
   56     exc_info = [esc(str(value)) for value in sys.exc_info()[:2]]
   57     l = [_('<h1>Templating Error</h1>\n'
   58            '<p><b>%(exc_type)s</b>: %(exc_value)s</p>\n'
   59            '<p class="help">Debugging information follows</p>'
   60            ) % {'exc_type': exc_info[0], 'exc_value': exc_info[1]},
   61          '<ol>', ]
   62     from roundup.cgi.PageTemplates.Expressions import TraversalError
   63     t = inspect.trace(context)
   64     t.reverse()
   65     for frame, file, lnum, func, lines, index in t:
   66         args, varargs, varkw, locals = inspect.getargvalues(frame)
   67         if '__traceback_info__' in locals:
   68             ti = locals['__traceback_info__']
   69             if isinstance(ti, TraversalError):
   70                 s = []
   71                 for name, info in ti.path:
   72                     s.append(_('<li>"%(name)s" (%(info)s)</li>')
   73                              % {'name': name, 'info': esc(repr(info))})
   74                 s = '\n'.join(s)
   75                 l.append(_('<li>Looking for "%(name)s", '
   76                            'current path:<ol>%(path)s</ol></li>'
   77                           ) % {'name': ti.name, 'path': s})
   78             else:
   79                 l.append(_('<li>In %s</li>') % esc(str(ti)))
   80         if '__traceback_supplement__' in locals:
   81             ts = locals['__traceback_supplement__']
   82             if len(ts) == 2:
   83                 supp, context = ts
   84                 s = _('A problem occurred in your template "%s".') \
   85                     % str(context.id)
   86                 if context._v_errors:
   87                     s = s + '<br>' + '<br>'.join(
   88                         [esc(x) for x in context._v_errors])
   89                 l.append('<li>%s</li>' % s)
   90             elif len(ts) == 3:
   91                 supp, context, info = ts
   92                 l.append(_('''
   93 <li>While evaluating the %(info)r expression on line %(line)d
   94 <table class="otherinfo" style="font-size: 90%%">
   95  <tr><th colspan="2" class="header">Current variables:</th></tr>
   96  %(globals)s
   97  %(locals)s
   98 </table></li>
   99 ''') % {
  100     'info': info,
  101     'line': context.position[0],
  102     'globals': niceDict('    ', context.global_vars),
  103     'locals': niceDict('    ', context.local_vars)
  104 })
  105 
  106     l.append('''
  107 </ol>
  108 <table style="font-size: 80%%; color: gray">
  109  <tr><th class="header" align="left">%s</th></tr>
  110  <tr><td><pre>%s</pre></td></tr>
  111 </table>''' % (_('Full traceback:'), html_escape(''.join(
  112         traceback.format_exception(*sys.exc_info())
  113     ))))
  114     l.append('<p>&nbsp;</p>')
  115     return '\n'.join(l)
  116 
  117 
  118 def html(context=5, i18n=None):
  119     _ = get_translator(i18n)
  120     etype, evalue = sys.exc_info()[0], sys.exc_info()[1]
  121     if type(etype) is type:
  122         etype = etype.__name__
  123     pyver = 'Python ' + sys.version.split()[0] + '<br>' + sys.executable
  124     head = pydoc.html.heading(
  125         _('<font size=+1><strong>%(exc_type)s</strong>: %(exc_value)s</font>')
  126         % {'exc_type': etype, 'exc_value': evalue},
  127         '#ffffff', '#777777', pyver)
  128 
  129     head = head + (_('<p>A problem occurred while running a Python script. '
  130                      'Here is the sequence of function calls leading up to '
  131                      'the error, with the most recent (innermost) call first. '
  132                      'The exception attributes are:'))
  133 
  134     indent = '<tt><small>%s</small>&nbsp;</tt>' % ('&nbsp;' * 5)
  135     traceback = []
  136     for frame, file, lnum, func, lines, index in inspect.trace(context):
  137         if file is None:
  138             link = _("&lt;file is None - probably inside <tt>eval</tt> "
  139                      "or <tt>exec</tt>&gt;")
  140         else:
  141             file = os.path.abspath(file)
  142             link = '<a href="file:%s">%s</a>' % (file, pydoc.html.escape(file))
  143         args, varargs, varkw, locals = inspect.getargvalues(frame)
  144         if func == '?':
  145             call = ''
  146         else:
  147             call = _('in <strong>%s</strong>') % \
  148                    func + inspect.formatargvalues(
  149                        args, varargs, varkw, locals,
  150                        formatvalue=lambda value: '=' + pydoc.html.repr(value))
  151 
  152         level = '''
  153 <table width="100%%" bgcolor="#dddddd" cellspacing=0 cellpadding=2 border=0>
  154 <tr><td>%s %s</td></tr></table>''' % (link, call)
  155 
  156         if index is None or file is None:
  157             traceback.append('<p>' + level)
  158             continue
  159 
  160         # do a file inspection
  161         names = []
  162 
  163         def tokeneater(type, token, start, end, line, names=names):
  164             if type == tokenize.NAME and token not in keyword.kwlist:
  165                 if token not in names:
  166                     names.append(token)
  167             if type == tokenize.NEWLINE: raise IndexError
  168 
  169         def linereader(file=file, lnum=[lnum]):
  170             line = s2b(linecache.getline(file, lnum[0]))
  171             lnum[0] = lnum[0] + 1
  172             return line
  173 
  174         # The interface that is tokenize.tokenize in Python 3 is
  175         # called tokenize.generate_tokens in Python 2.  However,
  176         # Python 2 has tokenize.tokenize with a different interface,
  177         # and Python 3 has an undocumented generate_tokens function,
  178         # also with a different interface, so a version check is
  179         # needed instead of checking for which functions exist.
  180         if sys.version_info[0] > 2:
  181             tokenize_fn = tokenize.tokenize
  182         else:
  183             tokenize_fn = tokenize.generate_tokens
  184         try:
  185             for t in tokenize_fn(linereader):
  186                 tokeneater(*t)
  187         except IndexError:
  188             pass
  189         lvals = []
  190         for name in names:
  191             if name in frame.f_code.co_varnames:
  192                 if name in locals:
  193                     value = pydoc.html.repr(locals[name])
  194                 else:
  195                     value = _('<em>undefined</em>')
  196                 name = '<strong>%s</strong>' % name
  197             else:
  198                 if name in frame.f_globals:
  199                     value = pydoc.html.repr(frame.f_globals[name])
  200                 else:
  201                     value = _('<em>undefined</em>')
  202                 name = '<em>global</em> <strong>%s</strong>' % name
  203             lvals.append('%s&nbsp;= %s' % (name, value))
  204         if lvals:
  205             lvals = ', '.join(lvals)
  206             lvals = indent + '<small><font color="#909090">%s'\
  207                 '</font></small><br>' % lvals
  208         else:
  209             lvals = ''
  210 
  211         excerpt = []
  212         i = lnum - index
  213         for line in lines:
  214             number = '&nbsp;' * (5-len(str(i))) + str(i)
  215             number = '<small><font color="#909090">%s</font></small>' % number
  216             line = '<tt>%s&nbsp;%s</tt>' % (number, pydoc.html.preformat(line))
  217             if i == lnum:
  218                 line = '''
  219 <table width="100%%" bgcolor="white" cellspacing=0 cellpadding=0 border=0>
  220 <tr><td>%s</td></tr></table>''' % line
  221             excerpt.append('\n' + line)
  222             if i == lnum:
  223                 excerpt.append(lvals)
  224             i = i + 1
  225         traceback.append('<p>' + level + '\n'.join(excerpt))
  226 
  227     traceback.reverse()
  228 
  229     exception = '<p><strong>%s</strong>: %s' % (str(etype), str(evalue))
  230     attribs = []
  231     for name in dir(evalue):
  232         value = pydoc.html.repr(getattr(evalue, name))
  233         attribs.append('<br>%s%s&nbsp;= %s' % (indent, name, value))
  234 
  235     return head + ' '.join(attribs) + ' '.join(traceback) + '<p>&nbsp;</p>'
  236 
  237 
  238 def handler():
  239     print(breaker())
  240     print(html())
  241 
  242 # vim: set filetype=python ts=4 sw=4 et si :