Пример #1
0
 def dispatch_repr(self, obj, recursive):
     if obj is helper:
         return text_('<span class="help">%r</span>' % helper)
     if isinstance(obj, (int, long, float, complex)):
         return text_('<span class="number">%r</span>' % obj)
     if PY3:
         if isinstance(obj, text_type):
             return self.py3_text_repr(obj)
         if isinstance(obj, binary_type):
             return self.py3_binary_repr(obj)
     else:
         if isinstance(obj, basestring):
             return self.py2_string_repr(obj)
     if isinstance(obj, RegexType):
         return self.regex_repr(obj)
     if isinstance(obj, list):
         return self.list_repr(obj, recursive)
     if isinstance(obj, tuple):
         return self.tuple_repr(obj, recursive)
     if isinstance(obj, set):
         return self.set_repr(obj, recursive)
     if isinstance(obj, frozenset):
         return self.frozenset_repr(obj, recursive)
     if isinstance(obj, dict):
         return self.dict_repr(obj, recursive)
     if deque is not None and isinstance(obj, deque):
         return self.deque_repr(obj, recursive)
     return self.object_repr(obj)
Пример #2
0
 def dispatch_repr(self, obj, recursive):
     if obj is helper:
         return text_('<span class="help">%r</span>' % helper)
     if isinstance(obj, (int, long, float, complex)):
         return text_('<span class="number">%r</span>' % obj)
     if PY3:
         if isinstance(obj, text_type):
             return self.py3_text_repr(obj)
         if isinstance(obj, binary_type):
             return self.py3_binary_repr(obj)
     else:
         if isinstance(obj, basestring):
             return self.py2_string_repr(obj)
     if isinstance(obj, RegexType):
         return self.regex_repr(obj)
     if isinstance(obj, list):
         return self.list_repr(obj, recursive)
     if isinstance(obj, tuple):
         return self.tuple_repr(obj, recursive)
     if isinstance(obj, set):
         return self.set_repr(obj, recursive)
     if isinstance(obj, frozenset):
         return self.frozenset_repr(obj, recursive)
     if isinstance(obj, dict):
         return self.dict_repr(obj, recursive)
     if deque is not None and isinstance(obj, deque):
         return self.deque_repr(obj, recursive)
     return self.object_repr(obj)
Пример #3
0
 def generate_plaintext_traceback(self):
     """Like the plaintext attribute but returns a generator"""
     yield text_('Traceback (most recent call last):')
     for frame in self.frames:
         yield text_('  File "%s", line %s, in %s' %
                     (frame.filename, frame.lineno, frame.function_name))
         yield text_('    ' + frame.current_line.strip())
     yield text_(self.exception)
Пример #4
0
 def fallback_repr(self):
     try:
         info = ''.join(format_exception_only(*sys.exc_info()[:2]))
     except Exception:  # pragma: no cover
         info = '?'
     return text_('<span class="brokenrepr">&lt;broken repr (%s)&gt;'
                  '</span>' %
                  escape(text_(info, 'utf-8', 'ignore').strip()))
Пример #5
0
 def fallback_repr(self):
     try:
         info = ''.join(format_exception_only(*sys.exc_info()[:2]))
     except Exception: # pragma: no cover
         info = '?'
     return text_(
         '<span class="brokenrepr">&lt;broken repr (%s)&gt;'
         '</span>' % escape(text_(info, 'utf-8', 'ignore').strip())
     )
Пример #6
0
 def generate_plaintext_traceback(self):
     """Like the plaintext attribute but returns a generator"""
     yield text_('Traceback (most recent call last):')
     for frame in self.frames:
         yield text_('  File "%s", line %s, in %s' % (
             frame.filename,
             frame.lineno,
             frame.function_name
             ))
         yield text_('    ' + frame.current_line.strip())
     yield self.exception
Пример #7
0
 def py3_binary_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     escaped = escape(text_(obj, 'utf-8', 'replace'))
     a = repr(escaped[:limit])
     b = repr(escaped[limit:])
     buf.append('b')
     if b != "''":
         buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
     else:
         buf.append(a)
     buf.append('</span>')
     return _add_subclass_info(text_(''.join(buf)), obj, binary_type)
Пример #8
0
 def py3_binary_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     escaped = escape(text_(obj, 'utf-8', 'replace'))
     a = repr(escaped[:limit])
     b = repr(escaped[limit:])
     buf.append('b')
     if b != "''":
         buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
     else:
         buf.append(a)
     buf.append('</span>')
     return _add_subclass_info(text_(''.join(buf)), obj, binary_type)
Пример #9
0
 def regex_repr(self, obj):
     if PY3:
         pattern = text_("'%s'" % str(obj.pattern), 'string-escape', 'ignore')
         pattern = 'r' + pattern
     else:
         pattern = text_(repr(obj.pattern), 'string-escape', 'ignore')
         if pattern[:1] == 'u':
             pattern = 'ur' + pattern[1:]
         else:
             pattern = 'r' + pattern
     return text_(
         're.compile(<span class="string regex">%s</span>)' % pattern)
Пример #10
0
 def regex_repr(self, obj):
     if PY3:
         pattern = text_("'%s'" % str(obj.pattern), 'string-escape',
                         'ignore')
         pattern = 'r' + pattern
     else:
         pattern = text_(repr(obj.pattern), 'string-escape', 'ignore')
         if pattern[:1] == 'u':
             pattern = 'ur' + pattern[1:]
         else:
             pattern = 'r' + pattern
     return text_('re.compile(<span class="string regex">%s</span>)' %
                  pattern)
Пример #11
0
    def __init__(self, exc_type, exc_value, tb, context=None):
        self.lineno = tb.tb_lineno
        self.function_name = tb.tb_frame.f_code.co_name
        self.locals = tb.tb_frame.f_locals
        self.globals = tb.tb_frame.f_globals
        self.context = context

        fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
        if fn[-4:] in ('.pyo', '.pyc'):
            fn = fn[:-1]
            # if it's a file on the file system resolve the real filename.
        if os.path.isfile(fn):
            fn = os.path.realpath(fn)
        self.filename = fn
        self.module = self.globals.get('__name__')
        self.loader = self.globals.get('__loader__')
        self.code = tb.tb_frame.f_code

        # support for paste's traceback extensions
        self.hide = self.locals.get('__traceback_hide__', False)
        info = self.locals.get('__traceback_info__')
        if info is not None:
            try:
                info = text_(info)
            except UnicodeError:
                info = str(info).decode('utf-8', 'replace')
        self.info = info
Пример #12
0
    def __init__(self, exc_type, exc_value, tb, context=None):
        if inspect.isframe(tb):
            self.lineno = tb.f_lineno
            tb_frame = tb
        else:
            self.lineno = tb.tb_lineno
            tb_frame = tb.tb_frame

        self.function_name = tb_frame.f_code.co_name
        self.locals = tb_frame.f_locals
        self.globals = tb_frame.f_globals
        self.context = context

        fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
        if fn[-4:] in ('.pyo', '.pyc'):
            fn = fn[:-1]
            # if it's a file on the file system resolve the real filename.
        if os.path.isfile(fn):
            fn = os.path.realpath(fn)
        self.filename = fn
        self.module = self.globals.get('__name__')
        self.loader = self.globals.get('__loader__')
        self.code = tb_frame.f_code

        # support for paste's traceback extensions
        self.hide = self.locals.get('__traceback_hide__', False)
        info = self.locals.get('__traceback_info__')
        if info is not None:
            try:
                info = text_(info)
            except UnicodeError:
                info = str(info).decode('utf-8', 'replace')
        self.info = info
Пример #13
0
 def dict_repr(self, d, recursive, limit=5):
     if recursive:
         return _add_subclass_info(text_('{...}'), d, dict)
     buf = ['{']
     have_extended_section = False
     for idx, (key, value) in enumerate(iteritems_(d)):
         if idx:
             buf.append(', ')
         if idx == limit - 1:
             buf.append('<span class="extended">')
             have_extended_section = True
         buf.append('<span class="pair"><span class="key">%s</span>: '
                    '<span class="value">%s</span></span>' %
                    (self.repr(key), self.repr(value)))
     if have_extended_section:
         buf.append('</span>')
     buf.append('}')
     return _add_subclass_info(text_(''.join(buf)), d, dict)
Пример #14
0
 def dict_repr(self, d, recursive, limit=5):
     if recursive:
         return _add_subclass_info(text_('{...}'), d, dict)
     buf = ['{']
     have_extended_section = False
     for idx, (key, value) in enumerate(iteritems_(d)):
         if idx:
             buf.append(', ')
         if idx == limit - 1:
             buf.append('<span class="extended">')
             have_extended_section = True
         buf.append('<span class="pair"><span class="key">%s</span>: '
                    '<span class="value">%s</span></span>' %
                    (self.repr(key), self.repr(value)))
     if have_extended_section:
         buf.append('</span>')
     buf.append('}')
     return _add_subclass_info(text_(''.join(buf)), d, dict)
Пример #15
0
    def assemble_email(self, traceback):
        msg = MIMEMultipart()

        subject = text_(traceback.exception)

        msg['Subject'] = text_(self.error_subject_prefix + subject)
        msg['From'] = text_(self.from_address)
        msg['To'] = text_(', '.join(self.error_email))

        text = MIMEText(bytes_(self.email_body(traceback)), 'plain', 'utf-8')
        text.set_type('text/plain')
        text.set_param('charset', 'UTF-8')
        msg.attach(text)

        request = traceback.context.get('request')
        if self.dump_request and request is not None:
            part = MIMEApplication(request.as_bytes(self.dump_request_size))
            part.add_header('Content-Disposition', 'attachment; filename="request.txt"')
            msg.attach(part)

        return msg
Пример #16
0
    def assemble_email(self, traceback):
        msg = MIMEMultipart()

        subject = text_(traceback.exception)

        msg['Subject'] = text_(self.error_subject_prefix + subject)
        msg['From'] = text_(self.from_address)
        msg['To'] = text_(', '.join(self.error_email))

        text = MIMEText(bytes_(self.email_body(traceback)), 'plain', 'utf-8')
        text.set_type('text/plain')
        text.set_param('charset', 'UTF-8')
        msg.attach(text)

        request = traceback.context.get('request')
        if self.dump_request and request is not None:
            part = MIMEApplication(request.as_bytes(self.dump_request_size))
            part.add_header('Content-Disposition',
                            'attachment; filename="request.txt"')
            msg.attach(part)

        return msg
Пример #17
0
 def __call__(self, topic=None):
     if topic is None:
         sys.stdout._write('<span class=help>%s</span>' % repr(self))
         return
     import pydoc
     pydoc.help(topic)
     rv = text_(sys.stdout.reset(), 'utf-8', 'ignore')
     paragraphs = _paragraph_re.split(rv)
     if len(paragraphs) > 1:
         title = paragraphs[0]
         text = '\n\n'.join(paragraphs[1:])
     else:  # pragma: no cover
         title = 'Help'
         text = paragraphs[0]
     sys.stdout._write(HELP_HTML % {'title': title, 'text': text})
Пример #18
0
 def __call__(self, topic=None):
     if topic is None:
         sys.stdout._write('<span class=help>%s</span>' % repr(self))
         return
     import pydoc
     pydoc.help(topic)
     rv = text_(sys.stdout.reset(), 'utf-8', 'ignore')
     paragraphs = _paragraph_re.split(rv)
     if len(paragraphs) > 1:
         title = paragraphs[0]
         text = '\n\n'.join(paragraphs[1:])
     else: # pragma: no cover
         title = 'Help'
         text = paragraphs[0]
     sys.stdout._write(HELP_HTML % {'title': title, 'text': text})
Пример #19
0
 def py2_string_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     escaped = escape(obj)
     a = repr(escaped[:limit])
     b = repr(escaped[limit:])
     if isinstance(obj, text_type):
         buf.append('u')
         a = a[1:]
         b = b[1:]
     if b != "''":
         buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
     else:
         buf.append(a)
     buf.append('</span>')
     return _add_subclass_info(text_('').join(buf), obj, (str, unicode))
Пример #20
0
 def py2_string_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     escaped = escape(obj)
     a = repr(escaped[:limit])
     b = repr(escaped[limit:])
     if isinstance(obj, text_type):
         buf.append('u')
         a = a[1:]
         b = b[1:]
     if b != "''":
         buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
     else:
         buf.append(a)
     buf.append('</span>')
     return _add_subclass_info(text_('').join(buf), obj, (str, unicode))
Пример #21
0
 def proxy(self, obj, recursive):
     if recursive:
         return _add_subclass_info(left + '...' + right, obj, base)
     buf = [left]
     have_extended_section = False
     for idx, item in enumerate(obj):
         if idx:
             buf.append(', ')
         if idx == limit:
             buf.append('<span class="extended">')
             have_extended_section = True
         buf.append(self.repr(item))
     if have_extended_section:
         buf.append('</span>')
     buf.append(right)
     return _add_subclass_info(text_(''.join(buf)), obj, base)
Пример #22
0
 def proxy(self, obj, recursive):
     if recursive:
         return _add_subclass_info(left + '...' + right, obj, base)
     buf = [left]
     have_extended_section = False
     for idx, item in enumerate(obj):
         if idx:
             buf.append(', ')
         if idx == limit:
             buf.append('<span class="extended">')
             have_extended_section = True
         buf.append(self.repr(item))
     if have_extended_section:
         buf.append('</span>')
     buf.append(right)
     return _add_subclass_info(text_(''.join(buf)), obj, base)
Пример #23
0
 def render(self):
     return SOURCE_LINE_HTML % {
         'classes': text_(' ').join(self.classes),
         'lineno': self.lineno,
         'code': escape(self.code)
     }
Пример #24
0
_line_re = re.compile(r'^(.*?)$(?m)')
_funcdef_re = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
UTF8_COOKIE = '\xef\xbb\xbf'

HEADER = text_('''\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>%(title)s // Backlash</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css" type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does not by
         accident trigger a request to /favicon.ico which might change the application
         state. -->
    <link rel="shortcut icon" href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
    <script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script type="text/javascript">
      var TRACEBACK = %(traceback_id)d,
          CONSOLE_MODE = %(console)s,
          EVALEX = %(evalex)s,
          SECRET = "%(secret)s";
    </script>
  </head>
  <body>
    <div class="debugger">
''')

FOOTER = text_('''\
      <div class="footer">
        <strong class="arthur">Backlash</strong>, using
Пример #25
0
 def object_repr(self, obj):
     return text_('<span class="object">%s</span>' %
                  escape(text_(repr(obj), 'utf-8', 'replace')))
Пример #26
0
    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ''
        description = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <em>(most recent call last)</em>:')

        for frame in self.frames:
            frames.append(text_('<li%s>%s') % (
                frame.info and text_(' title="%s"') % escape(frame.info) or text_(''),
                frame.render()
                ))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')

        return SUMMARY_HTML % {
            'classes':      text_(' '.join(classes)),
            'title':        title and text_('<h3>%s</h3>' % title) or text_(''),
            'frames':       text_('\n'.join(frames)),
            'description':  description_wrapper % escape(self.exception)
        }
Пример #27
0
 def plaintext(self):
     return text_('\n'.join(self.generate_plaintext_traceback()))
Пример #28
0
_funcdef_re = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
UTF8_COOKIE = '\xef\xbb\xbf'


HEADER = text_('''\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>%(title)s // Backlash</title>
    <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css" type="text/css">
    <!-- We need to make sure this has a favicon so that the debugger does not by
         accident trigger a request to /favicon.ico which might change the application
         state. -->
    <link rel="shortcut icon" href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png">
    <script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script>
    <script type="text/javascript" src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script>
    <script type="text/javascript">
      var TRACEBACK = %(traceback_id)d,
          CONSOLE_MODE = %(console)s,
          EVALEX = %(evalex)s,
          SECRET = "%(secret)s";
    </script>
  </head>
  <body>
    <div class="debugger">
''')

FOOTER = text_('''\
      <div class="footer">
        <strong class="arthur">Backlash</strong>, using
Пример #29
0
 def render(self):
     return SOURCE_LINE_HTML % {
         'classes':      text_(' ').join(self.classes),
         'lineno':       self.lineno,
         'code':         escape(self.code)
     }
Пример #30
0
 def _write(self, x):
     if isinstance(x, binary_type):
         x = text_(x, 'utf-8', 'replace')
     self._buffer.append(x)
Пример #31
0
 def render_source(self):
     """Render the sourcecode."""
     return SOURCE_TABLE_HTML % text_('\n'.join(
         line.render() for line in self.get_annotated_lines()))
Пример #32
0
    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ''
        description = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = text_('Syntax Error')
            else:
                title = text_('Traceback <em>(most recent call last)</em>:')

        for frame in self.frames:
            frames.append(
                text_('<li%s>%s') %
                (frame.info and text_(' title="%s"') % escape(frame.info)
                 or text_(''), frame.render()))

        if self.is_syntax_error:
            description_wrapper = text_('<pre class=syntaxerror>%s</pre>')
        else:
            description_wrapper = text_('<blockquote>%s</blockquote>')

        return SUMMARY_HTML % {
            'classes': text_(' '.join(classes)),
            'title': title and text_('<h3>%s</h3>' % title) or text_(''),
            'frames': text_('\n'.join(frames)),
            'description': description_wrapper % escape(self.exception)
        }
Пример #33
0
 def _write(self, x):
     if isinstance(x, binary_type):
         x = text_(x, 'utf-8', 'replace')
     self._buffer.append(x)
Пример #34
0
 def object_repr(self, obj):
     return text_('<span class="object">%s</span>' %
                  escape(text_(repr(obj), 'utf-8', 'replace')))
Пример #35
0
 def render_source(self):
     """Render the sourcecode."""
     return SOURCE_TABLE_HTML % text_('\n'.join(line.render() for line in
         self.get_annotated_lines()))
Пример #36
0
 def plaintext(self):
     return text_('\n'.join(self.generate_plaintext_traceback()))
Пример #37
0
 def current_line(self):
     try:
         return self.sourcelines[self.lineno - 1]
     except IndexError:
         return text_('')
Пример #38
0
 def current_line(self):
     try:
         return self.sourcelines[self.lineno - 1]
     except IndexError:
         return text_('')