Exemple #1
0
def execActionMsg(request, appSlug, actionSlug, actionAttrs, **args):
    """
    Executes an action and shows a message of result of action.
    """
    logger.debug("execActionMsg :: appslug: %s actionslug: %s actionAttrs: %s" % (appSlug, actionSlug, actionAttrs))
    dbApplication = ApplicationDAO(args["ctx"])
    application = dbApplication.get(slug=appSlug)
    db = ActionDAO(args["ctx"])
    action = db.get(application=application, slug=actionSlug)
    impl = action.implementation
    implFields = impl.split(".")
    method = implFields[len(implFields) - 1]
    classPath = ".".join(implFields[:-1])
    args["ctx"].path = "/apps/" + application.slug + "/" + action.slug
    if actionAttrs.find("/") != -1:
        actionAttrTuple = actionAttrs.split("/")
    else:
        if len(actionAttrs) == 0:
            actionAttrTuple = []
        else:
            actionAttrTuple = [actionAttrs]
    # Instance and call method for view, get result
    if method.find("_") == -1 or method.find("__") == -1:
        cls = get_class(classPath)
        obj = cls(args["ctx"])
        super(cls, obj).__init__(args["ctx"])
        obj.request = request
        if len(actionAttrTuple) == 0:
            result = eval("obj." + method)()
        else:
            result = eval("obj." + method)(*actionAttrTuple)
    else:
        logger.debug("xpcore :: execAction :: private methods...")
        raise Http404
    return result
Exemple #2
0
def showView(request, appSlug="front", viewSlug="home", viewAttrs="", **args):
    """
    Show url view. Application code and view name are parsed from the url.
    urls not following /appSlug/viewSlug mapped into urls???? appSlug would be default app from settings

    **Required Attributes**

    **Optional Attributes**

    **Returns**

    """
    # logger.debug( 'xpcore showView :: context: %s' % (json.dumps(args['ctx'])) )
    dbApplication = ApplicationDAO(args["ctx"])
    application = dbApplication.get(slug=appSlug)
    db = ViewDAO(args["ctx"])
    view = db.get(application=application, slug=viewSlug)
    args["ctx"].viewAuth = view.hasAuth
    classPath, method, viewAttrTuple = __showView(view, viewAttrs, args["ctx"])
    if method.find("_") == -1 or method.find("__") == -1:
        logger.debug("showView :: classPath: %s method: %s viewAttrTuple: %s" % (classPath, method, viewAttrTuple))
        cls = get_class(classPath)
        obj = cls(args["ctx"])
        super(cls, obj).__init__(args["ctx"])
        obj.request = request
        if len(viewAttrTuple) == 0:
            result = eval("obj." + method)()
        else:
            result = eval("obj." + method)(*viewAttrTuple)
    else:
        logger.debug("xpcore :: showView :: private methods...")
        raise Http404
    return result
Exemple #3
0
def jxDataSwitchOrder(request, **args):
    """
    Change order in a data table

    ** Attributes **

    * ``request``
    * ``args``

    ** Html Attributes **

    * ``dbClass``:str
    * ``orderCurrent``:str ????
    * ``orderNew``:str
    * ``pk``

    """
    logger.debug("jxDataSwitchOrder...")
    # TODO: Hit master for this operation
    # get current order
    # get list fields from current order to new order
    # new order higher or lower than current order?
    orderCurrent = int(request.REQUEST["orderCurrent"])
    orderNew = int(request.REQUEST["orderCurrent"])
    pk = request.REQUEST["pk"]
    dbClass = request.REQUEST["dbClass"]
    orderField = "order"
    if request.REQUEST.has_key("orderField"):
        orderField = request.REQUEST["orderField"]
    logger.debug(
        "jxDataSwitchOrder :: pk: %s orderCurrent: %s orderNew: %s dbClass: %s" % (pk, orderCurrent, orderNew, dbClass)
    )
    dbApplication = ApplicationDAO(args["ctx"])
    app = request.REQUEST["app"]
    application = dbApplication.get(name=app)
    # app: ximpia_site.web, MyDAO => ximpia_site.web.data.MyDAO
    classPath = app + ".data." + dbClass
    cls = get_class(classPath)
    obj = cls(args["ctx"])  # @UnusedVariable
    item = obj.get(pk=pk)
    logger.debug("jxDataSwitchOrder :: change order : %s -> %s" % (orderCurrent, orderNew))
    item.__setattr__(orderField, orderNew)
    orderDbCurrent = eval("item." + orderField)
    logger.debug("jxDataSwitchOrder :: orderDbCurrent: %s" % (orderDbCurrent))
    if orderCurrent != orderDbCurrent:
        raise XpMsgException(None, _("Sorting error. Please retry later. Thanks"))
    if orderNew > orderCurrent:
        # Moving down the list
        logger.debug("jxDataSwitchOrder :: Moving down the list...")
        itemsToUpdate = obj.objects.filter(order__gt=orderCurrent, order__lte=orderNew).values()
        logger.debug("jxDataSwitchOrder :: itemsToUpdate. %s" % (itemsToUpdate))
        for itemToUpdate in itemsToUpdate:
            logger.debug(
                "jxDataSwitchOrder :: Move down: %s -> %s" % (itemToUpdate[orderField], itemToUpdate[orderField] - 1)
            )
            itemToUpdate[orderField] -= 1
            itemToUpdate.save()
    else:
        # Moving up the list
        logger.debug("jxDataSwitchOrder :: Moving up the list...")
        itemsToUpdate = obj.objects.filter(order__gt=orderNew, order__lt=orderCurrent).values()
        logger.debug("jxDataSwitchOrder :: itemsToUpdate. %s" % (itemsToUpdate))
        for itemToUpdate in itemsToUpdate:
            logger.debug(
                "jxDataSwitchOrder :: Move up: %s -> %s" % (itemToUpdate[orderField], itemToUpdate[orderField] + 1)
            )
            itemToUpdate[orderField] += 1
            itemToUpdate.save()
    logger.debug("jxDataSwitchOrder :: finished!!!")
    return HttpResponse(json.dumps("OK"))
Exemple #4
0
def jxService(request, **args):
    """Excutes the business class: bsClass, method {bsClass: '', method: ''}
    @param request: Request
    @param result: Result"""
    logger.debug("jxService...")
    # raw_input('Continue???')
    # time.sleep(1.5)
    logger.debug(json.dumps(request.REQUEST.items()))
    request.session.set_test_cookie()
    request.session.delete_test_cookie()
    # logger.debug( 'session: %s' % (json.dumps(request.session.items())) )
    # logger.debug( 'session: %s' % json.dumps(request.session.items()) + ' ' + json.dumps(request.session.session_key) )
    if (request.REQUEST.has_key("view") or request.REQUEST.has_key("action")) and request.is_ajax() is True:
        viewAttrs = {}
        dbApplication = ApplicationDAO(args["ctx"])
        app = request.REQUEST["app"]
        application = dbApplication.get(name=app)
        if request.REQUEST.has_key("view"):
            view = request.REQUEST["view"]
            logger.debug("view: %s" % (view))
            dbView = ViewDAO(args["ctx"])
            viewObj = dbView.get(application__name=app, name=view)
            args["ctx"].viewAuth = viewObj.hasAuth
            impl = viewObj.implementation
            # view attributes
            viewAttrs = json.loads(request.REQUEST["params"]) if "params" in request.REQUEST else {}
            args["ctx"].viewNameSource = view
            args["ctx"].path = "/apps/" + application.slug + "/" + viewObj.slug
        elif request.REQUEST.has_key("action"):
            action = request.REQUEST["action"]
            logger.debug("action: %s" % (action))
            dbAction = ActionDAO(args["ctx"])
            dbView = ViewDAO(args["ctx"])
            actionObj = dbAction.get(application__name=app, name=action)
            # if args['ctx'].has_key('viewNameSource') and len(args['ctx']['viewNameSource']) != 0:
            if len(args["ctx"].viewNameSource) != 0:
                # Get view name and check its application code with application code of action
                logger.debug("viewNameSource: %s" % (args["ctx"].viewNameSource))
                viewObj = dbView.get(application__name=app, name=args["ctx"].viewNameSource)
                if actionObj.application.name != viewObj.application.name:
                    raise XpMsgException(None, _("Action is not in same application as view source"))
            impl = actionObj.implementation
            args["ctx"].path = "/apps/" + application.slug + "/do/" + actionObj.slug
        implFields = impl.split(".")
        method = implFields[len(implFields) - 1]
        classPath = ".".join(implFields[:-1])
        logger.debug("classPath: %s" % (classPath))
        if method.find("_") == -1 or method.find("__") == -1:
            cls = get_class(classPath)
            obj = cls(args["ctx"])
            super(cls, obj).__init__(args["ctx"])
            obj.request = request
            if len(viewAttrs) == 0:
                result = getattr(obj, method)()
            else:
                result = getattr(obj, method)(**viewAttrs)
        else:
            logger.debug("private methods...")
            raise Http404
    else:
        logger.debug("Unvalid business request")
        raise Http404
    return result
Exemple #5
0
def jxDataQuery(request, **args):
    """
    Execute data queries for lists with ordering, page and filters.

    ** Attributes **

    * ``request``
    * ``args``

    ** Html Attributes **

    * ``dbClass``:str : Data class name (DAO)
    * ``fields``:list<str> [optional]
    * ``pageStart``:str [optional] [default:1] : Start page number
    * ``pageEnd``:str [optional] : End page number
    * ``orderBy``:tuple<str> [optional]
    * ``method``:str [optional] [default:searchFields]
    * ``args``:dict<str,str> [optional]
    * ``hasOrdering``:bool [optional]
    * ``orderField``:str [optional]

    ** Returns **

    result
    """
    logger.debug("jxDataQuery...")
    logger.debug("jxDataQuery :: args: %s" % (args))
    logger.debug("jxDataQuery :: REQUEST: %s" % (request.REQUEST))
    if not request.REQUEST.has_key("dbClass") or not request.REQUEST.has_key("app"):
        raise XpMsgException(AttributeError, _("app and dbClass must be defined."))
    dbClass = request.REQUEST["dbClass"]
    dbApplication = ApplicationDAO(args["ctx"])
    # logger.debug('jxDataQuery :: app: {}'.format(request.REQUEST['app'], get_app_full_path(request.REQUEST['app'])))
    app = get_app_full_path(request.REQUEST["app"])
    application = dbApplication.get(name=app)
    # app: ximpia_site.web, MyDAO => ximpia_site.web.data.MyDAO
    classPath = app + ".data." + dbClass
    cls = get_class(classPath)
    obj = cls(args["ctx"])  # @UnusedVariable
    obj.request = request
    logger.debug("jxDataQuery :: obj: %s" % (obj))
    # fields
    fields = []
    if request.REQUEST.has_key("fields"):
        fields = json.loads(request.REQUEST["fields"])
    dbArgs = {}
    meta = AttrDict()
    # disablePaging
    dbArgs["disable_paging"] = False
    if request.REQUEST.has_key("disablePaging"):
        dbArgs["disable_paging"] = json.loads(request.REQUEST["disablePaging"])
    if not dbArgs["disable_paging"]:
        if request.REQUEST.has_key("pageStart"):
            dbArgs["page_start"] = int(request.REQUEST["pageStart"])
        else:
            dbArgs["page_start"] = 1
        logger.debug("jxDataQuery :: pageStart: %s" % (dbArgs["page_start"]))
    # pageEnd
    if request.REQUEST.has_key("pageEnd") and not dbArgs["disable_paging"]:
        dbArgs["page_end"] = int(request.REQUEST["pageEnd"])
    # orderBy
    if request.REQUEST.has_key("orderBy"):
        dbArgs["order_by"] = json.loads(request.REQUEST["orderBy"])
    # args
    if request.REQUEST.has_key("args"):
        requestArgs = json.loads(request.REQUEST["args"])
        for requestArg in requestArgs:
            try:
                dbArgs[requestArg] = json.loads(requestArgs[requestArg])
            except ValueError:
                dbArgs[requestArg] = requestArgs[requestArg]
    # numberResults
    if request.REQUEST.has_key("numberResults"):
        dbArgs["number_results"] = int(request.REQUEST["numberResults"])
    else:
        # Get number results from settings
        dbArgs["number_results"] = int(Setting.objects.get(name__name=KSite.SET_NUMBER_RESULTS_LIST).value)
    logger.debug("jxDataQuery :: numberResults: %s" % (dbArgs["number_results"]))

    # hasOrdering
    if request.REQUEST.has_key("hasOrdering") and request.REQUEST["hasOrdering"] == "true":
        if request.REQUEST.has_key("orderField"):
            fields.append(request.REQUEST["orderField"])
        else:
            fields.append("order")
    # hasHeader
    hasHeader = False
    if request.REQUEST.has_key("hasHeader"):
        hasHeader = json.loads(request.REQUEST["hasHeader"])
    logger.debug("jxDataQuery :: hasHeader: %s" % (hasHeader))
    if "id" not in fields and len(fields) != 0:
        fields.insert(0, "id")
    logger.debug("jxDataQuery :: fields: %s" % (fields))
    logger.debug("jxDataQuery :: dbArgs: %s" % (dbArgs))

    """dbArgs['disablePaging'] = False
    dbArgs['pageStart'] = 1
    dbArgs['pageEnd'] = 1
    dbArgs['numberResults'] = 2"""

    if request.REQUEST.has_key("method"):
        dataListTmp = eval("obj." + request.REQUEST["method"])(fields, **dbArgs)
    else:
        dataListTmp = obj.search_fields(fields, **dbArgs)
    # numberPages
    if dbArgs["disable_paging"] is not True:
        dbArgsPages = copy.copy(dbArgs)
        if dbArgsPages.has_key("page_start"):
            del dbArgsPages["page_start"]
        if dbArgsPages.has_key("page_end"):
            del dbArgsPages["page_end"]
        if request.REQUEST.has_key("method"):
            """dataListTmp = eval('obj.' + request.REQUEST['method'])(fields, **dbArgsPages)
            logger.debug('jxDataQuery :: type dataListTmp: %s' % (type(dataListTmp)) )
            meta.numberPages = dataListTmp.count()/numberResults"""
            pass
        else:
            if dbArgsPages.has_key("disable_paging"):
                del dbArgsPages["disable_paging"]
            if dbArgsPages.has_key("number_results"):
                numberResults = dbArgsPages["number_results"]
                del dbArgsPages["number_results"]
            if dbArgsPages.has_key("page_start"):
                del dbArgsPages["page_start"]
            if dbArgsPages.has_key("page_end"):
                del dbArgsPages["page_end"]
            if dbArgsPages.has_key("order_by"):
                del dbArgsPages["order_by"]
            meta.numberPages = int(round(float(obj.model.objects.filter(**dbArgsPages).count()) / float(numberResults)))
    else:
        meta.numberPages = 1

    meta.pageStart = 1
    if dbArgs.has_key("page_start"):
        meta.pageStart = dbArgs["page_start"]
    if dbArgs.has_key("page_end"):
        meta.pageEnd = dbArgs["page_end"]
    else:
        meta.pageEnd = meta.pageStart
    # logger.debug('jxDataQuery :: dataListTmp: %s' % (dataListTmp) )
    dataList = []
    for dbFields in dataListTmp:
        ll = []
        for dbField in dbFields:
            if type(dbField) == datetime.date:
                ll.append(dbField.strftime("%m/%d/%Y"))
            elif type(dbField) == datetime.datetime:
                ll.append(dbField.strftime("%m/%d/%Y %H:%M"))
            elif type(dbField) == datetime.time:
                ll.append(dbField.strftime("%H:%M"))
            else:
                ll.append(dbField)
        dataList.append(ll)
    logger.debug("jxDataQuery :: dataList: %s" % (dataList))
    # headers
    headers = []
    if hasHeader:
        modelFields = obj.model._meta.fields
        logger.debug("jxDataQuery :: modelFields: %s" % (modelFields))
        if len(fields) == 0:
            # get all model fields from table and add to headers
            for modelField in modelFields:
                headers.append(modelField.verbose_name)
        else:
            # Get model fields with max level 3: field__field__field
            for field in fields:
                if field.count("__") == 0:
                    headerField = obj.model._meta.get_field_by_name(field)[0].verbose_name
                    logger.debug("jxDataQuery :: headerField: %s" % (headerField))
                    headers.append(headerField)
                elif field.count("__") == 1:
                    fieldFrom, fieldTo = field.split("__")
                    logger.debug("jxDataQuery :: fieldFrom: %s fieldTo: %s" % (fieldFrom, fieldTo))
                    """relField = obj.model._meta.get_field_by_name(fieldFrom)[0]\
                        .rel.to._meta.get_field_by_name(fieldTo)[0]"""
                    # 03/07/2013 : We get header name from fk verbose name and not linked to verbose name
                    relField = obj.model._meta.get_field_by_name(fieldFrom)[0]
                    if type(relField.verbose_name) == types.UnicodeType:
                        headerField = relField.verbose_name
                    else:
                        headerField = relField.name
                    logger.debug("jxDataQuery :: headerField: %s" % (headerField))
                    headers.append(headerField)
                elif field.count("__") == 2:
                    fieldFrom, fieldTo1, fieldTo2 = field.split("__")
                    logger.debug("jxDataQuery :: fieldFrom: %s fieldTo: %s" % (fieldFrom, fieldTo1, fieldTo2))
                    """relField = obj.model._meta.get_field_by_name(fieldFrom)[0]\
                        .rel.to._meta.get_field_by_name(fieldTo1)[0]\
                        .rel.to._meta.get_field_by_name(fieldTo2)[0]"""
                    # 03/07/2013 : We get header name from fk verbose name and not linked to verbose name
                    relField = obj.model._meta.get_field_by_name(fieldFrom)[0]
                    if type(relField.verbose_name) == types.UnicodeType:
                        headerField = relField.verbose_name
                    else:
                        headerField = relField.name
                    logger.debug("jxDataQuery :: headerField: %s" % (headerField))
                    headers.append(headerField)
    logger.debug("jxDataQuery :: headers: %s" % (headers))
    results = {"headers": headers, "data": dataList, "meta": meta}
    logger.debug("jxDataQuery :: results: %s" % (results))
    return HttpResponse(json.dumps(results))