gluon.serializers.jsons

Here are the examples of the python api gluon.serializers.jsons taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3 Examples 7

Example 1

Project: eden Source File: s3dashboard.py
Function: configure
    def configure(self, dashboard, context):
        """
            Controller for the widget configuration dialog

            @param dashboard: the calling S3Dashboard instance
            @param context: the S3DashboardContext

            @return: output dict for the view
        """

        response = current.response
        s3 = response.s3

        # Get the form fields from the widget class
        prototype = self.widget
        formfields = prototype.configure(self)

        # The current configuration as formdata
        formdata = dict(self.config)
        formdata["id"] = 0

        # Form buttons
        T = current.T
        submit_btn = INPUT(_class = "tiny primary button submit-btn",
                           _name = "submit",
                           _type = "submit",
                           _value = T("Submit"),
                           )
        buttons = [submit_btn]

        # Construct the form
        settings = s3.crud
        formstyle = settings.formstyle
        form = SQLFORM.factory(*formfields,
                               record = formdata,
                               showid = False,
                               formstyle = formstyle,
                               table_name = "config",
                               upload = s3.download_url,
                               separator = "",
                               submit_button = settings.submit_button,
                               buttons = buttons)

        # Process the form
        formname = "config/%s" % self.agent_id
        if form.accepts(context.post_vars,
                        current.session,
                        onvalidation = prototype.validate_config,
                        formname = formname,
                        keepvalues = False,
                        hideerror = False,
                        ):

            # Get an updated config dict from the widget
            widget_config = self.config
            widget_id = widget_config.get("widget_id")

            new_config = prototype.accept_config(widget_config, form)

            # Pass new config to client via s3.popup_data
            popup_data = {"c": new_config}

            # Save the new config and add the new version key to the popup_data
            if dashboard:
                version = dashboard.config.save(context, {widget_id: new_config})
                if version:
                    popup_data["v"] = version

            # Using JSON serializer rather than raw json.dumps to catch T()'s
            from gluon.serializers import json as jsons
            s3.popup_data = jsons(popup_data)

            # Send a confirmation so the popup gets closed
            # (layout.html diverts to layout_popup.html with
            # "popup" request format + response.confirmation)
            response.confirmation = T("Configuration updated")

        # Set view (@todo: implement specific view?)
        response.view = "popup.html"

        return {# Context needed for layout.html to determine
                # the representation format:
                "r": context,
                "form": form,
                }

Example 2

Project: eden Source File: s3export.py
Function: json
    def json(self, resource,
             start=None,
             limit=None,
             fields=None,
             orderby=None,
             represent=False,
             tooltip=None):
        """
            Export a resource as JSON

            @param resource: the resource to export from
            @param start: index of the first record to export
            @param limit: maximum number of records to export
            @param fields: list of field selectors for fields to include in
                           the export (None for all fields)
            @param orderby: ORDERBY expression
            @param represent: whether values should be represented
            @param tooltip: additional tooltip field, either a field selector
                            or an expression "f(k,v)" where f is a function
                            name that can be looked up from s3db, and k,v are
                            field selectors for the row, f will be called with
                            a list of tuples (k,v) for each row and is expected
                            to return a dict {k:tooltip} => used by
                            filterOptionsS3 to extract onhover-tooltips for
                            Ajax-update of options
        """

        if fields is None:
            # Use json_fields setting, or fall back to list_fields if
            # not defined, or to all readable fields if list_fields is
            # not defined either.
            # Always include the ID field regardless whether it is
            # configured or not => required for S3FilterOptions and
            # similar Ajax lookups.
            fields = resource.list_fields("json_fields", id_column=0)

        if orderby is None:
            orderby = resource.get_config("orderby", None)

        tooltip_function = None
        if tooltip:
            if type(tooltip) is list:
                tooltip = tooltip[-1]
            import re
            match = re.match("(\w+)\((\w+),(\w+)\)", tooltip)
            if match:
                function_name, kname, vname = match.groups()
                # Try to resolve the function name
                tooltip_function = current.s3db.get(function_name)
                if tooltip_function:
                    if kname not in fields:
                        fields.append(kname)
                    if vname not in fields:
                        fields.append(vname)
            else:
                if tooltip not in fields:
                    fields.append(tooltip)

        # Get the data
        _rows = resource.select(fields,
                                start=start,
                                limit=limit,
                                orderby=orderby,
                                represent=represent).rows

        # Simplify to plain fieldnames for fields in this table
        tn = "%s." % resource.tablename
        rows = []
        rappend = rows.append
        for _row in _rows:
            row = {}
            for f in _row:
                v = _row[f]
                if tn in f:
                    f = f.split(tn, 1)[1]
                row[f] = v
            rappend(row)

        if tooltip:
            if tooltip_function:
                # Resolve key and value names against the resource
                try:
                    krfield = resource.resolve_selector(kname)
                    vrfield = resource.resolve_selector(vname)
                except (AttributeError, SyntaxError):
                    import sys
                    current.log.error(sys.exc_info()[1])
                else:
                    # Extract key and value fields from each row and
                    # build options dict for function call
                    options = []
                    items = {}
                    for row in rows:
                        try:
                            k = krfield.extract(row)
                        except KeyError:
                            break
                        try:
                            v = vrfield.extract(row)
                        except KeyError:
                            break
                        items[k] = row
                        options.append((k, v))
                    # Call tooltip rendering function
                    try:
                        tooltips = tooltip_function(options)
                    except:
                        import sys
                        current.log.error(sys.exc_info()[1])
                    else:
                        # Add tooltips as "_tooltip" to the corresponding rows
                        if isinstance(tooltips, dict):
                            from s3utils import s3_unicode
                            for k, v in tooltips.items():
                                if k in items:
                                    items[k]["_tooltip"] = s3_unicode(v)

            else:
                # Resolve the tooltip field name against the resource
                try:
                    tooltip_rfield = resource.resolve_selector(tooltip)
                except (AttributeError, SyntaxError):
                    import sys
                    current.log.error(sys.exc_info()[1])
                else:
                    # Extract the tooltip field from each row
                    # and add it as _tooltip
                    from s3utils import s3_unicode
                    for row in rows:
                        try:
                            value = tooltip_rfield.extract(row)
                        except KeyError:
                            break
                        if value:
                            row["_tooltip"] = s3_unicode(value)

        # Return as JSON
        response = current.response
        if response:
            response.headers["Content-Type"] = "application/json"

        from gluon.serializers import json as jsons
        return jsons(rows)

Example 3

Project: eden Source File: tour.py
def tour_builder(output):
    """
         Helper function to attach a guided tour (if required) to the output
    """

    auth = current.auth
    db = current.db
    s3db = current.s3db
    request = current.request
    s3 = current.response.s3
    T = current.T

    req_vars = request.vars
    tour_id = req_vars.tour
    # Now see if the details are on the database for this user
    tour = None
    user_id = None
    if auth.is_logged_in():
        user_id = auth.s3_logged_in_person()
        # Find out if the user has done this tour before
        utable = s3db.tour_user
        uquery = (utable.person_id == user_id) & \
                (utable.tour_config_id == tour_id)
        tour = db(uquery).select(utable.id,
                                utable.completed,
                                utable.place,
                                utable.resume,
                                limitby=(0, 1)).first()
        # If the tour has just been started (from the menu) then
        # it may be necessary to redirect to a different controller
        # @todo: does place need to be changed to controller and function?
        if not req_vars.tour_running:
            if (tour and not tour.completed and tour.place != request.controller):
                redirect("%s?tour=%s" %(tour.resume, tour_id))

    # get the details from the database
    dtable = s3db.tour_details
    dquery = (dtable.tour_config_id == tour_id) &\
            (dtable.controller == request.controller) &\
            (dtable.function == request.function)
    details = db(dquery).select(dtable.args,
                               dtable.tip_title,
                               dtable.tip_details,
                               dtable.button,
                               dtable.tip_location,
                               dtable.html_id,
                               dtable.html_class,
                               dtable.datatable_id,
                               dtable.datatable_row,
                               dtable.redirect,
                               orderby=(dtable.posn)
                               )
#        tour_filename = os.path.join(request.folder,
#                                     "private",
#                                     "tour",
#                                     tour_name)
#        tour_file = open (tour_filename, "rb")
#        # now open the details of the guided_tour into a dictionary
#        import csv
#        tour_details = csv.DictReader(tour_file, skipinitialspace=True)
    # load the list of tour items in the html
    joyride_OL = OL(_id="joyrideID_1")
    pre_step_data = []
    post_step_data = []
    post_ride_data = []
    last_row = None
    last_used = None
    req_args = request.args
    cnt = -1
    for row in details:
        if row.args:
            args = row.args.split(",")
        else:
            args = []
        # if the page has a nested login form then "login" will be added to
        # the req_args list so it needs to be added to the args list as well
        if "login" in req_args:
            if "login" not in args:
                args.append("login")
        # The following will capture the actual id used for the req_arg
        # Example org/organisation/10, where 10 is the id from the database
        posn = 0
        for arg in args:
            if arg == "dt_id":
                args[posn] = req_args[posn]
            posn += 1
        # Now check that the tour url matches the current url
        if (args == req_args):
            cnt += 1 # number of records used in this part of the tour
            if row.datatable_id:
                dt_id = row.datatable_id
#                    cols = []
#                    if "DataTable_columns" in row:
#                        cols = row["DataTable_columns"].split(",")
                row_num = 0
                if row.datatable_row:
                    row_num = row.datatable_row
                # Now set this up for the pre-processor hook in joyride
                pre_step_data.append([cnt, dt_id, row_num])
            if row.redirect:
                redirect_row = row.redirect.split(",")
                if len(redirect_row) >= 3:
                    url = URL(c=redirect_row[0],
                              f=redirect_row[1],
                              args=redirect_row[2:],
                              vars={"tour_running":True,
                                    "tour":tour_id}
                              )
                    if "dt_id" in redirect_row[2]:
                        post_step_data.append([cnt, url, dt_id, row_num])
                elif len(redirect_row) == 2:
                    url = URL(c=redirect_row[0],
                              f=redirect_row[1],
                              vars={"tour_running":True,
                                    "tour":tour_id}
                              )
                    post_step_data.append([cnt, url])
                else:
                    url = URL(c=redirect_row[0],vars={"tour_running":True,
                                                  "tour":tour_id})
                    post_step_data.append([cnt, url])
            extra = {}
            if row.html_id:
                extra["_data-id"] = row.html_id
            elif row.html_class:
                extra["_data-class"] = row.html_class
            if row.button:
                extra["_data-button"] = row.button
            else:
                extra["_data-button"] = "Next"
            if row.tip_location:
                extra["_data-options"] = "tipLocation:%s" % row.tip_location.lower()
            else:
                extra["_data-options"] = "tipLocation:right"
            joyride_OL.append(LI(H2(T(row.tip_title)),
                                 P(T(row.tip_details)),
                                    **extra
                                 )
                              )
            last_used = row
        last_row = row
    # The following redirect will be triggered if the user has moved away
    # from the tour, such as by clicking on a tab. However if a tab
    # is part of the tour we are unable to determine if they have moved
    # away or just visiting as part of the tour and so it will continue.
    if len(joyride_OL) == 0:
        del request.vars.tour
        redirect(URL(args=req_args,
                     vars=request.vars))
    if (user_id != None) and (last_row == last_used):
        # set up an AJAX call to record that the tour has been completed
        post_ride_data = [cnt, tour_id]
    joyride_div = DIV(joyride_OL,
                      _class="hidden")
    # Add the javascript configuration data
    from gluon.serializers import json as jsons
    if pre_step_data:
        joyride_div.append(INPUT(_type="hidden",
                                 _id="prestep_data",
                                 _name="prestep_data",
                                 _value=jsons(pre_step_data))
                           )
    if post_step_data:
        joyride_div.append(INPUT(_type="hidden",
                                 _id="poststep_data",
                                 _name="poststep_data",
                                 _value=jsons(post_step_data))
                           )
    if post_ride_data:
        joyride_div.append(INPUT(_type="hidden",
                                 _id="postride_data",
                                 _name="postride_data",
                                 _value=jsons(post_ride_data))
                           )
    # Now add the details to the tour_user table
    if user_id != None:
        if tour == None:
            # this user has never done this tour before so create a new record
            utable.insert(person_id = user_id,
                          tour_config_id = tour_id,
                          place = request.controller,
                          resume = request.url)
        else:
            # the user has done some of this tour so update the record
            db(uquery).update(place = request.controller,
                             resume = request.url,
                             completed = False)

    output["joyride_div"] = joyride_div
    if s3.debug:
        appname = request.application
        s3.scripts.append("/%s/static/scripts/jquery.joyride.js" % appname)
        s3.scripts.append("/%s/static/scripts/S3/s3.guidedtour.js" % appname)
        s3.stylesheets.append("plugins/joyride.min.css")
    else:
        s3.scripts.append("/%s/static/scripts/S3/s3.guidedtour.min.js" % request.application)
        s3.stylesheets.append("plugins/joyride.css")
    return output