Ejemplo n.º 1
0
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL
     BUTTON = TAG.button
     admin = URL("admin",
                 "default",
                 "design",
                 args=current.request.application)
     from gluon.dal import thread
     dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
                            for row in i.db._timings]) \
                    for i in thread.instances]
     u = web2py_uuid()
     return DIV(
         BUTTON('design', _onclick="document.location='%s'" % admin),
         BUTTON('request',
                _onclick="jQuery('#request-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.request),
             _class="hidden",
             _id="request-%s" % u),
         BUTTON('session',
                _onclick="jQuery('#session-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.session),
             _class="hidden",
             _id="session-%s" % u),
         BUTTON('response',
                _onclick="jQuery('#response-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.response),
             _class="hidden",
             _id="response-%s" % u),
         BUTTON('db stats',
                _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
         DIV(BEAUTIFY(dbstats), _class="hidden", _id="db-stats-%s" % u),
         SCRIPT("jQuery('.hidden').hide()"))
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL
     BUTTON = TAG.button
     admin = URL("admin","default","design",
                 args=current.request.application)
     from gluon.dal import thread
     if hasattr(thread,'instances'):
         dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
                                for row in i.db._timings]) \
                        for i in thread.instances]
         dbtables = dict([(i.uri, {'defined': sorted(list(set(i.db.tables) - 
                                              set(i.db._LAZY_TABLES.keys()))) or
                                              '[no defined tables]',
                                   'lazy': sorted(i.db._LAZY_TABLES.keys()) or
                                           '[no lazy tables]'})
                          for i in thread.instances])
     else:
         dbstats = [] # if no db or on GAE
         dbtables = {}
     u = web2py_uuid()
     return DIV(
         BUTTON('design',_onclick="document.location='%s'" % admin),
         BUTTON('request',_onclick="jQuery('#request-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.request),_class="hidden",_id="request-%s"%u),
         BUTTON('session',_onclick="jQuery('#session-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.session),_class="hidden",_id="session-%s"%u),
         BUTTON('response',_onclick="jQuery('#response-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.response),_class="hidden",_id="response-%s"%u),
         BUTTON('db tables',_onclick="jQuery('#db-tables-%s').slideToggle()"%u),
         DIV(BEAUTIFY(dbtables),_class="hidden",_id="db-tables-%s"%u),
         BUTTON('db stats',_onclick="jQuery('#db-stats-%s').slideToggle()"%u),
         DIV(BEAUTIFY(dbstats),_class="hidden",_id="db-stats-%s"%u),
         SCRIPT("jQuery('.hidden').hide()")
         )
Ejemplo n.º 3
0
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL, A
     BUTTON = TAG.button
     admin = URL("admin",
                 "default",
                 "design",
                 args=current.request.application)
     from gluon.dal import DAL
     dbstats = []
     dbtables = {}
     infos = DAL.get_instances()
     for k, v in infos.iteritems():
         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)
     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(current.request),
                    backtotop,
                    _class="hidden",
                    _id="request-%s" % u),
                DIV(BEAUTIFY(current.session),
                    backtotop,
                    _class="hidden",
                    _id="session-%s" % u),
                DIV(BEAUTIFY(current.response),
                    backtotop,
                    _class="hidden",
                    _id="response-%s" % u),
                DIV(BEAUTIFY(dbtables),
                    backtotop,
                    _class="hidden",
                    _id="db-tables-%s" % u),
                DIV(BEAUTIFY(dbstats),
                    backtotop,
                    _class="hidden",
                    _id="db-stats-%s" % u),
                SCRIPT("jQuery('.hidden').hide()"),
                _id="totop-%s" % u)
    def widget(field, value, **attributes):
        _id = '%s_%s' % (field._tablename, field.name)
        _name = field.name
        if field.type == 'list:integer': _class = 'integer'
        else: _class = 'string'
        items=[LI(INPUT(_id=_id,_class=_class,_name=_name,value=v,hideerror=True)) \
                   for v in value or ['']]
        script = SCRIPT("""
// from http://refactormycode.com/codes/694-expanding-input-list-using-jquery
(function(){
jQuery.fn.grow_input = function() {
  return this.each(function() {
    var ul = this;
    jQuery(ul).find(":text").keypress(function (e) { return (e.which == 13) ? pe(ul) : true; });
  });
};
function pe(ul) {
  var new_line = ml(ul);
  rel(ul);
  new_line.appendTo(ul);
  new_line.find(":text").focus();
  return false;
}
function ml(ul) {
  var line = jQuery(ul).find("li:first").clone(true);
  line.find(':text').val('');
  return line;
}
function rel(ul) {
  jQuery(ul).find("li").each(function() {
    var trimmed = jQuery.trim(jQuery(this.firstChild).val());
    if (trimmed=='') jQuery(this).remove(); else jQuery(this.firstChild).val(trimmed);
  });
}
})();
jQuery(document).ready(function(){jQuery('#%s_grow_input').grow_input();});
""" % _id)
        attributes['_id'] = _id + '_grow_input'
        return TAG[''](UL(*items, **attributes), script)
Ejemplo n.º 5
0
def LOAD(c=None, f='index', args=None, vars=None,
         extension=None, target=None,ajax=False,ajax_trap=False,
         url=None,user_signature=False, timeout=None, times=1,
         content='loading...',**attr):
    """  LOAD a component into the action's document

    Timing options:
    -times: An integer or string ("infinity"/"continuous")
    specifies how many times the component is requested
    -timeout (milliseconds): specifies the time to wait before
    starting the request or the frequency if times is greater than
    1 or "infinity".
    Timing options default to the normal behavior. The component
    is added on page loading without delay.
    """
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None: args = []
    vars = Storage(vars or {})
    target = target or 'c'+str(random.random())[2:]
    attr['_id']=target
    request = current.request
    if '.' in f:
        f, extension = f.rsplit('.',1)
    if url or ajax:
        url = url or URL(request.application, c, f, r=request,
                         args=args, vars=vars, extension=extension,
                         user_signature=user_signature)
        # timing options
        if isinstance(times, basestring):
            if times.upper() in ("INFINITY", "CONTINUOUS"):
                times = "Infinity"
            else:
                raise TypeError("Unsupported times argument %s" % times)
        elif isinstance(times, int):
            if times <= 0:
                raise ValueError("Times argument must be greater than zero, 'Infinity' or None")
        else:
            raise TypeError("Unsupported times argument type %s" % type(times))
        if timeout is not None:
            if not isinstance(timeout, (int, long)):
                raise ValueError("Timeout argument must be an integer or None")
            elif timeout <= 0:
                raise ValueError("Timeout argument must be greater than zero or None")
            statement = "web2py_component('%s','%s', %s, %s);" \
            % (url, target, timeout, times)
        else:
            statement = "web2py_component('%s','%s');" % (url, target)
        script = SCRIPT(statement, _type="text/javascript")
        if not content is None:
            return TAG[''](script, DIV(content,**attr))
        else:
            return TAG[''](script)

    else:
        if not isinstance(args,(list,tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage(request)
        other_request['env'] = Storage(request.env)
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = Storage()
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application,c,f] + \
                         map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_response.view = '%s/%s.%s' % (c,f, other_request.extension)

        other_environment = copy.copy(current.globalenv) ### NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            other_response._view_environment.update(page)
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application, c, f, r=request,
                            args=args, vars=vars, extension=extension,
                            user_signature=user_signature)
            js = "web2py_trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js,_type="text/javascript") or ''
        return TAG[''](DIV(XML(page),**attr),script)
Ejemplo n.º 6
0
def LOAD(c=None,
         f='index',
         args=None,
         vars=None,
         extension=None,
         target=None,
         ajax=False,
         ajax_trap=False,
         url=None,
         user_signature=False,
         timeout=None,
         times=1,
         content='loading...',
         post_vars=Storage(),
         **attr):
    """  LOADs a component into the action's document

    Args:
        c(str): controller
        f(str): function
        args(tuple or list): arguments
        vars(dict): vars
        extension(str): extension
        target(str): id of the target
        ajax(bool): True to enable AJAX bahaviour
        ajax_trap(bool): True if `ajax` is set to `True`, traps
            both links and forms "inside" the target
        url(str): overrides `c`,`f`,`args` and `vars`
        user_signature(bool): adds hmac signature to all links
            with a key that is different for every user
        timeout(int): in milliseconds, specifies the time to wait before
            starting the request or the frequency if times is greater than
            1 or "infinity"
        times(integer or str): how many times the component will be requested
            "infinity" or "continuous" are accepted to reload indefinitely the
            component
    """
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None:
        args = []
    vars = Storage(vars or {})
    target = target or 'c' + str(random.random())[2:]
    attr['_id'] = target
    request = current.request
    if '.' in f:
        f, extension = f.rsplit('.', 1)
    if url or ajax:
        url = url or URL(request.application,
                         c,
                         f,
                         r=request,
                         args=args,
                         vars=vars,
                         extension=extension,
                         user_signature=user_signature)
        # timing options
        if isinstance(times, basestring):
            if times.upper() in ("INFINITY", "CONTINUOUS"):
                times = "Infinity"
            else:
                raise TypeError("Unsupported times argument %s" % times)
        elif isinstance(times, int):
            if times <= 0:
                raise ValueError(
                    "Times argument must be greater than zero, 'Infinity' or None"
                )
        else:
            raise TypeError("Unsupported times argument type %s" % type(times))
        if timeout is not None:
            if not isinstance(timeout, (int, long)):
                raise ValueError("Timeout argument must be an integer or None")
            elif timeout <= 0:
                raise ValueError(
                    "Timeout argument must be greater than zero or None")
            statement = "$.web2py.component('%s','%s', %s, %s);" \
                % (url, target, timeout, times)
            attr['_data-w2p_timeout'] = timeout
            attr['_data-w2p_times'] = times
        else:
            statement = "$.web2py.component('%s','%s');" % (url, target)
        attr['_data-w2p_remote'] = url
        if not target is None:
            return DIV(content, **attr)

    else:
        if not isinstance(args, (list, tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage(request)
        other_request['env'] = Storage(request.env)
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = post_vars
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application, c, f] +
                     map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_request.restful = types.MethodType(
            request.restful.im_func, other_request
        )  # A bit nasty but needed to use LOAD on action decorates with @request.restful()
        other_response.view = '%s/%s.%s' % (c, f, other_request.extension)

        other_environment = copy.copy(current.globalenv)  # NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            other_response._view_environment.update(page)
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application,
                       c,
                       f,
                       r=request,
                       args=args,
                       vars=vars,
                       extension=extension,
                       user_signature=user_signature)
            js = "$.web2py.trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js, _type="text/javascript") or ''
        return TAG[''](DIV(XML(page), **attr), script)
Ejemplo n.º 7
0
def LOAD(c=None, f='index', args=None, vars=None,
         extension=None, target=None,ajax=False,ajax_trap=False,
         url=None,user_signature=False, content='loading...',**attr):
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None: args = []
    vars = Storage(vars or {})
    target = target or 'c'+str(random.random())[2:]
    attr['_id']=target
    request = current.request
    if '.' in f:
        f, extension = f.split('.',1)
    if url or ajax:
        url = url or URL(request.application, c, f, r=request,
                         args=args, vars=vars, extension=extension,
                         user_signature=user_signature)
        script = SCRIPT('web2py_component("%s","%s")' % (url, target),
                             _type="text/javascript")
        return TAG[''](script, DIV(content,**attr))
    else:
        if not isinstance(args,(list,tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage()
        for key, value in request.items():
            other_request[key] = value
        other_request['env'] = Storage()
        for key, value in request.env.items():
            other_request.env['key'] = value
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = Storage()
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application,c,f] + \
                         map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_response.view = '%s/%s.%s' % (c,f, other_request.extension)

        other_environment = copy.copy(current.globalenv) ### NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            for key in page:
                other_response._view_environment[key] = page[key]
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application, c, f, r=request,
                            args=args, vars=vars, extension=extension,
                            user_signature=user_signature)
            js = "web2py_trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js,_type="text/javascript") or ''
        return TAG[''](DIV(XML(page),**attr),script)