Exemple #1
0
 def toolbar(self):
     from gluon.html import DIV, SCRIPT, BEAUTIFY, TAG, A
     BUTTON = TAG.button
     admin = URL("admin", "default", "design", extension='html',
                 args=current.request.application)
     from gluon.dal import DAL
     dbstats = []
     dbtables = {}
     infos = DAL.get_instances()
     for k, v in iteritems(infos):
         dbstats.append(TABLE(*[TR(PRE(row[0]), '%.2fms' % (row[1]*1000))
                                for row in v['dbstats']]))
         dbtables[k] = dict(defined=v['dbtables']['defined'] or '[no defined tables]',
                            lazy=v['dbtables']['lazy'] or '[no lazy tables]')
     u = web2py_uuid()
     backtotop = A('Back to top', _href="#totop-%s" % u)
     # Convert lazy request.vars from property to Storage so they
     # will be displayed in the toolbar.
     request = copy.copy(current.request)
     request.update(vars=current.request.vars,
                    get_vars=current.request.get_vars,
                    post_vars=current.request.post_vars)
     return DIV(
         BUTTON('design', _onclick="document.location='%s'" % admin),
         BUTTON('request',
                _onclick="jQuery('#request-%s').slideToggle()" % u),
         BUTTON('response',
                _onclick="jQuery('#response-%s').slideToggle()" % u),
         BUTTON('session',
                _onclick="jQuery('#session-%s').slideToggle()" % u),
         BUTTON('db tables',
                _onclick="jQuery('#db-tables-%s').slideToggle()" % u),
         BUTTON('db stats',
                _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
         DIV(BEAUTIFY(request), backtotop,
             _class="w2p-toolbar-hidden", _id="request-%s" % u),
         DIV(BEAUTIFY(current.session), backtotop,
             _class="w2p-toolbar-hidden", _id="session-%s" % u),
         DIV(BEAUTIFY(current.response), backtotop,
             _class="w2p-toolbar-hidden", _id="response-%s" % u),
         DIV(BEAUTIFY(dbtables), backtotop,
             _class="w2p-toolbar-hidden", _id="db-tables-%s" % u),
         DIV(BEAUTIFY(dbstats), backtotop,
             _class="w2p-toolbar-hidden", _id="db-stats-%s" % u),
         SCRIPT("jQuery('.w2p-toolbar-hidden').hide()"),
         _id="totop-%s" % u
     )
Exemple #2
0
 def test_BEAUTIFY(self):
     #self.assertEqual(BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml(),
     #                 '<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>')
     # unicode
     self.assertEqual(
         BEAUTIFY([P(u'àéèûôç'), 'a', 'b', {
             'hello': 'world'
         }]).xml(),
         b'<div><table><tr><td><div><p>\xc3\xa0\xc3\xa9\xc3\xa8\xc3\xbb\xc3\xb4\xc3\xa7</p></div></td></tr><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>'
     )
Exemple #3
0
def snapshot(info=None, context=5, code=None, environment=None):
    """Return a dict describing a given traceback (based on cgitb.text)."""
    import time
    import linecache
    import inspect
    import pydoc
    import cgitb

    # if no exception info given, get current:
    etype, evalue, etb = info or sys.exc_info()

    if isinstance(etype, ClassType):
        etype = etype.__name__

    # create a snapshot dict with some basic information
    s = {}
    s['pyver'] = 'Python ' + sys.version.split(
    )[0] + ': ' + sys.executable + ' (prefix: %s)' % sys.prefix
    s['date'] = time.ctime(time.time())

    # start to process frames
    records = inspect.getinnerframes(etb, context)
    del etb  # Prevent circular references that would cause memory leaks
    s['frames'] = []
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = inspect.formatargvalues(
                args,
                varargs,
                varkw,
                locals,
                formatvalue=lambda value: '=' + pydoc.text.repr(value))

        # basic frame information
        f = {
            'file': file,
            'func': func,
            'call': call,
            'lines': {},
            'lnum': lnum
        }

        highlight = {}

        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try:
                return linecache.getline(file, lnum[0])
            finally:
                lnum[0] += 1

        vars = cgitb.scanvars(reader, frame, locals)

        # if it is a view, replace with generated code
        if file.endswith('html'):
            lmin = lnum > context and (lnum - context) or 0
            lmax = lnum + context
            lines = code.split("\n")[lmin:lmax]
            index = min(context, lnum) - 1

        if index is not None:
            i = lnum - index
            for line in lines:
                f['lines'][i] = line.rstrip()
                i += 1

        # dump local variables (referenced in current line only)
        f['dump'] = {}
        for name, where, value in vars:
            if name in f['dump']:
                continue
            if value is not cgitb.__UNDEF__:
                if where == 'global':
                    name = 'global ' + name
                elif where != 'local':
                    name = where + name.split('.')[-1]
                f['dump'][name] = pydoc.text.repr(value)
            else:
                f['dump'][name] = 'undefined'

        s['frames'].append(f)

    # add exception type, value and attributes
    s['etype'] = str(etype)
    s['evalue'] = str(evalue)
    s['exception'] = {}
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            value = pydoc.text.repr(getattr(evalue, name))
            s['exception'][name] = value

    # add all local values (of last frame) to the snapshot
    s['locals'] = {}
    for name, value in locals.items():
        s['locals'][name] = pydoc.text.repr(value)

    # add web2py environment variables
    for k, v in environment.items():
        if k in ('request', 'response', 'session'):
            s[k] = XML(str(BEAUTIFY(v)))

    return s