Exemple #1
0
def phase_jsondata():
    table = DataTable(request.args, Phase, Phase.query,
                      ["id", "no", "name", "desc", "status_text"])
    table.searchable(lambda qs, sq: qs.filter(
        or_(Phase.name.contains(sq), Phase.no.contains(sq),
            Phase.desc.contains(sq))))
    return json.dumps(table.json())
Exemple #2
0
    def test_column_inputs(self):
        self.make_data(10)
        req = self.make_params()

        table = DataTable(req, User, self.session.query(User), [
            DataColumn(name="id", model_name="id", filter=None),
            ("full_name", lambda i: str(i)), "address"
        ])
        table.json()
Exemple #3
0
    def test_filter(self):
        self.make_data(10)
        req = self.make_params()

        table = DataTable(
            req, User, self.session.query(User),
            ["id", ("name", "full_name", lambda i: "User: "******"name"].startswith("User: "******"data"])
Exemple #4
0
    def test_extra_data(self):
        self.make_data(10)

        req = self.make_params()
        table = DataTable(req, User, self.session.query(User), ["id"])
        table.add_data(id_multiplied=lambda i: i.id * 10)

        result = table.json()
        assert all(r["id"] * 10 == r["DT_RowData"]["id_multiplied"]
                   for r in result["data"])
Exemple #5
0
    def test_column_inputs(self):
        self.make_data(10)
        req = self.make_params()

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              DataColumn(name="id", model_name="id", filter=None),
                              ("full_name", lambda i: str(i)),
                              "address"
                          ])
        table.json()
Exemple #6
0
    def test_filter(self):
        self.make_data(10)
        req = self.make_params()

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id",
                              ("name", "full_name", lambda i: "User: "******"name"].startswith("User: "******"data"])
Exemple #7
0
    def test_basic_function(self):
        self.make_data(10)

        req = self.make_params()

        table = DataTable(req, User, self.session.query(User), [
            "id",
            ("name", "full_name"),
            ("address", "address.description"),
        ])

        x = table.json()

        assert len(x["data"]) == 10
Exemple #8
0
    def test_extra_data(self):
        self.make_data(10)

        req = self.make_params()
        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id"
                          ])
        table.add_data(id_multiplied=lambda i: i.id * 10)

        result = table.json()
        assert all(r["id"] * 10 == r["DT_RowData"]["id_multiplied"] for r in result["data"])
Exemple #9
0
 def get(self):
     """
     Render and return JSON response for GET /ajax/ofx
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(
         args, OFXTransaction, db_session.query(OFXTransaction),
         [('date', 'date_posted',
           lambda i: i.date_posted.strftime('%Y-%m-%d')),
          ('amount', lambda a: float(a.amount)),
          ('account',
           'account.name', lambda i: "{} ({})".format(i.name, i.id)),
          ('type', 'trans_type'), 'name', 'memo', 'description', 'fitid',
          ('last_stmt', 'statement.id'),
          ('last_stmt_date', 'statement.as_of',
           lambda i: i.as_of.strftime('%Y-%m-%d')),
          ('reconcile_id', 'reconcile', lambda i: None
           if i.reconcile is None else i.reconcile.id)])
     table.add_data(acct_id=lambda o: o.account_id)
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
 def get(self):
     """
     Render and return JSON response for GET /ajax/ofx
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(args, Transaction, db_session.query(Transaction),
                       [('date', lambda i: i.date.strftime('%Y-%m-%d')),
                        ('amount', 'actual_amount',
                         lambda a: float(a.actual_amount)), 'description',
                        ('account', 'account.name',
                         lambda i: "{} ({})".format(i.name, i.id)),
                        ('scheduled', 'scheduled_trans_id'),
                        ('budgeted_amount'),
                        ('reconcile_id', 'reconcile', lambda i: None
                         if i.reconcile is None else i.reconcile.id)])
     table.add_data(
         acct_id=lambda o: o.account_id,
         budgets=lambda o: [{
             'name': bt.budget.name,
             'id': bt.budget_id,
             'amount': bt.amount,
             'is_income': bt.budget.is_income
         } for bt in sorted(
             o.budget_transactions, key=lambda x: x.amount, reverse=True)],
         id=lambda o: o.id)
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
Exemple #11
0
    def test_error(self):
        req = self.make_params()
        req["start"] = "invalid"

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          ["id"])
        assert "error" in table.json()

        req = self.make_params()
        del req["start"]

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          ["id"])
        assert "error" in table.json()
Exemple #12
0
def jsonhistory():
    history = db.session.query(models.Processed)
    table = DataTable(request.args, models.Processed, history, [
        ("date", "time", lambda i: "{}".format(i.time.strftime('%Y/%m/%d')) if i.stopped else '<span class="orange">{}</span>'.format(_("Currently watching..."))),
        ("ipaddress", lambda i: "{}".format(i.get_xml().find('Player').get("address"))),
        ("user", lambda i: '<a href="{0}" class="invert-link">{1}</a>'.format(url_for('user', name=i.user), i.user)),
        ("platform"),
        ("title", lambda i: u'<a class="invert-link" href="{0}">{1}</a>'.format(url_for('info', id=i.get_xml_value('ratingKey')), i.title)),
        ("type", lambda i: "{}".format(i.get_xml_value("type"))),
        ("streaminfo", lambda i: '<a href="#" data-link="{0}" class="orange" data-target="#streamModal" data-toggle="modal"><i class="glyphicon glyphicon glyphicon-info-sign"></i></a>'.format(url_for('streaminfo',id=i.id)) if i.platform != "Imported" else ''),
        ("time",lambda i: "{}".format(i.time.strftime('%H:%M'))),
        ("paused_counter", lambda i: "{} min".format(int(i.paused_counter)/60) if i.paused_counter else "0 min" ),
        ("stopped", lambda i: "{}".format(i.stopped.strftime('%H:%M')) if i.stopped else "n/a"),
        ("duration", lambda i: "{} min".format(int((((i.stopped - i.time).total_seconds() - (int(i.paused_counter or 0))) /60))) if i.stopped else "n/a"),
        ("completed", lambda i: '<span class="badge badge-warning">{}%</span>'.format(helper.getPercentage(i.get_xml_value("duration") if i.platform == "Imported" else i.get_xml_value("viewOffset"), i.get_xml_value("duration")))),
    ])
    table.searchable(lambda queryset, user_input: perform_some_search(queryset, user_input))

    return json.dumps(table.json())
Exemple #13
0
def data():
    table = DataTable(
        request.form, models.Mooch, db.session.query(models.Mooch),
        [("Image"),
         ("Name", "LastName",
          lambda i: "{}, {}".format(i.LastName, i.FirstName)), ("Affiliation"),
         ("Position"),
         ("Hired", "DateHired",
          lambda i: "{}".format(i.DateHired.strftime("%m/%d/%Y"))),
         ("Left", "DateLeft",
          lambda i: "{}".format(i.DateLeft.strftime("%m/%d/%Y"))),
         ("Total Days", "TotalTime", lambda i: "{:,}".format(
             (i.DateLeft - i.DateHired).days)),
         ("Under Trump", "TrumpTime",
          lambda i: "{:,}".format(models.trumpTime(i.DateHired, i.DateLeft))),
         ("Mooches", "MoochesTime"), ("Fired/Resign", "LeaveType"),
         ("Notes", lambda i: "{}".format(titlecase(i.Notes))), ("Sources")])
    table.searchable(
        lambda queryset, user_input: perform_search(queryset, user_input))
    return json.dumps(table.json())
Exemple #14
0
    def test_search(self):
        user, addr = self.make_user("Silly Sally", "Silly Sally Road")
        user2, addr2 = self.make_user("Silly Sall", "Silly Sally Roa")
        self.session.add_all((user, user2))
        self.session.commit()

        req = self.make_params(search={
            "value": "Silly Sally"
        })

        table = DataTable(req, User, self.session.query(User), [("name", "full_name")])
        results = table.json()
        assert len(results["data"]) == 1

        req = self.make_params(search={
            "value": "Silly Sall"
        })

        table = DataTable(req, User, self.session.query(User), [("name", "full_name")])
        results = table.json()
        assert len(results["data"]) == 2
Exemple #15
0
    def test_relation_ordering(self):
        self.make_data(10)
        u1, addr_asc = self.make_user("SomeUser", "0" * 15)
        u2, addr_desc = self.make_user("SomeOtherUser", "z" * 15)
        self.session.add_all((u1, u2))
        self.session.commit()

        req = self.make_params(order=[{"column": 2, "dir": "desc"}])
        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id",
                              ("name", "full_name"),
                              ("address", "address.description")
                          ])
        result = table.json()
        assert result["data"][0]["address"] == addr_desc.description

        req = self.make_params(order=[{"column": 2, "dir": "asc"}])
        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id",
                              ("name", "full_name"),
                              ("address", "address.description")
                          ])
        result = table.json()
        assert result["data"][0]["address"] == addr_asc.description
Exemple #16
0
    def test_ordering(self):
        self.make_data(10)
        desc_user, _ = self.make_user("z" * 20, "z" * 20)
        self.session.add(desc_user)
        self.session.commit()

        req = self.make_params(order=[{"column": 1, "dir": "desc"}])

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id",
                              ("name", "full_name"),
                              ("address", "address.description")
                          ])

        x = table.json()

        assert x["data"][0]["name"] == desc_user.full_name

        req = self.make_params(order=[{"column": 1, "dir": "asc"}], length=100)

        table = DataTable(req,
                          User,
                          self.session.query(User),
                          [
                              "id",
                              ("name", "full_name"),
                              ("address", "address.description")
                          ])

        x = table.json()

        assert x["data"][-1]["name"] == desc_user.full_name
Exemple #17
0
def jsonhistory():
    history = db.session.query(models.Processed)
    table = DataTable(request.args, models.Processed, history, [
        ("date", "time", lambda i: "{}".format(i.time.strftime('%Y/%m/%d'))
         if i.stopped else '<span class="orange">{}</span>'.format(
             _("Currently watching..."))),
        ("ipaddress",
         lambda i: "{}".format(i.get_xml().find('Player').get("address"))),
        ("user", lambda i: '<a href="{0}" class="invert-link">{1}</a>'.format(
            url_for('user', name=i.user), i.user)),
        ("platform"),
        ("title", lambda i: u'<a class="invert-link" href="{0}">{1}</a>'.
         format(url_for('info', id=i.get_xml_value('ratingKey')), i.title)),
        ("type", lambda i: "{}".format(i.get_xml_value("type"))),
        ("streaminfo", lambda i:
         '<a href="#" data-link="{0}" class="orange" data-target="#streamModal" data-toggle="modal"><i class="glyphicon glyphicon glyphicon-info-sign"></i></a>'
         .format(url_for('streaminfo', id=i.id))
         if i.platform != "Imported" else ''),
        ("time", lambda i: "{}".format(i.time.strftime('%H:%M'))),
        ("paused_counter",
         lambda i: "{} min".format(int(i.paused_counter) / 60)
         if i.paused_counter else "0 min"),
        ("stopped", lambda i: "{}".format(i.stopped.strftime('%H:%M'))
         if i.stopped else "n/a"),
        ("duration", lambda i: "{} min".format(
            int(((
                (i.stopped - i.time).total_seconds() -
                (int(i.paused_counter or 0))) / 60))) if i.stopped else "n/a"),
        ("completed",
         lambda i: '<span class="badge badge-warning">{}%</span>'.format(
             helper.getPercentage(
                 i.get_xml_value("duration") if i.platform == "Imported" else i
                 .get_xml_value("viewOffset"), i.get_xml_value("duration")))),
    ])
    table.searchable(
        lambda queryset, user_input: perform_some_search(queryset, user_input))

    return json.dumps(table.json())
Exemple #18
0
def request_group_tests(request):
    # Server side processing for DataTables plugin

    in_cases  = DBSession.query(TestGroupMembership.test_id).\
                filter(TestGroupMembership.group_id == request.matchdict['group_id'])
    not_cases = DBSession.query(TestCase).filter(~TestCase.id.in_(in_cases))

    table = DataTable(request.GET, TestCase, not_cases, ["id"])
    table.add_data(link=lambda o: request.route_url("view_test", test_id=o.id))
    table.searchable(lambda queryset, userinput: queryset.filter(
        TestCase.id.op('~')(userinput)))
    return table.json()
def compare_table(request):
    # Server Side processing for Datatables.

    res = DBSession.query(Run.test_id, Run.id.label('run_id'), aliased_run.id.label('alt_id'), Run.result, aliased_run.result.label("alt_result")).\
                            join(aliased_run, Run.test_id == aliased_run.test_id).\
                            filter(Run.job_id == request.matchdict['job_id_source']).\
                            filter(aliased_run.job_id == request.matchdict['job_id_dest']).\
                            filter(aliased_run.result != Run.result)

    table = DataTable(request.GET, Run, res, [("test_id"), ("run_id"), ("alt_id"), ("result"), ("alt_result")])
    table.add_data(link      =lambda o: request.route_url("view_test", test_id=o.test_id))
    table.add_data(sourcelink=lambda o: request.route_url("view_test_run", test_id=o.run_id))
    table.add_data(destlink  =lambda o: request.route_url("view_test_run", test_id=o.alt_id))
    table.searchable(lambda queryset, userinput: queryset.\
            filter(Run.test_id.op('~')(userinput)))
    return table.json()
def get_goods(purchase_id):

    param = request.args.to_dict()
    user = current_user.id
    user_purchase = db.session.query(UsersPurchase).filter(UsersPurchase.purchase_id == purchase_id).first()
    print(user_purchase.id)

    result = db.session.query(Goods.name, Goods.price).join(PurchaseConsist).filter(
        PurchaseConsist.purchase_id == user_purchase.id).all()
    for i in result:
        print(i.name)

    table = DataTable(param, Goods,
                      db.session.query(Goods.name, Goods.price).join(PurchaseConsist).filter(PurchaseConsist.purchase_id == user_purchase.id),
                      [
                          "name",
                          "price"
                          # ("edit", lambda
                          #     value: '<a class="btn btn-xs btn-block btn-info" href="%s"> <span class="glyphicon glyphicon-edit">'
                          #            '</span> Изменение</a>' % url_for('edit_class', class_id=value.id)),
                      ])

    return jsonify(table.json())
Exemple #21
0
    def test_search(self):
        user, addr = self.make_user("Silly Sally", "Silly Sally Road")
        user2, addr2 = self.make_user("Silly Sall", "Silly Sally Roa")
        self.session.add_all((user, user2))
        self.session.commit()

        req = self.make_params(search={"value": "Silly Sally"})

        table = DataTable(req, User, self.session.query(User),
                          [("name", "full_name")])
        table.searchable(
            lambda qs, sq: qs.filter(User.full_name.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 1

        req = self.make_params(search={"value": "Silly Sall"})

        table = DataTable(req, User, self.session.query(User),
                          [("name", "full_name")])
        table.searchable(
            lambda qs, sq: qs.filter(User.full_name.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 2
def request_group_tests(request):
     # Server side processing for DataTables plugin

    in_cases  = DBSession.query(TestGroupMembership.test_id).\
                filter(TestGroupMembership.group_id == request.matchdict['group_id'])
    not_cases = DBSession.query(TestCase).filter(~TestCase.id.in_(in_cases))

    table = DataTable(request.GET, TestCase, not_cases, ["id"])
    table.add_data(link=lambda o: request.route_url("view_test", test_id=o.id))
    table.searchable(lambda queryset, userinput: queryset.filter(TestCase.id.op('~')(userinput)))
    return table.json()
 def get(self):
     """
     Render and return JSON response for GET /ajax/projects
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(
         args, Project, db_session.query(Project),
         ['name', 'total_cost', 'remaining_cost', 'is_active', 'notes'])
     table.add_data(id=lambda o: o.id)
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
Exemple #24
0
    def test_error(self):
        req = self.make_params()
        req["start"] = "invalid"

        table = DataTable(req, User, self.session.query(User), ["id"])
        assert "error" in table.json()

        req = self.make_params()
        del req["start"]

        table = DataTable(req, User, self.session.query(User), ["id"])
        assert "error" in table.json()
Exemple #25
0
def request_job_table(request):
    # Server side processing for DataTables plugin

    job = request.matchdict['job_id']
    query = DBSession.query(Run.id, Run.test_id, Run.stdout, Run.stderr,
                            Run.result).filter(Run.job_id == job)

    resultFilter = request.params.getall('resultFilter[]')
    if resultFilter:
        query = query.filter(Run.result.in_(resultFilter))

    groupFilter = request.params.getall('select-group[]')
    if groupFilter:
        group_subquery = DBSession.query(TestGroupMembership.test_id) \
            .filter(TestGroupMembership.group_id.in_(groupFilter))
        query = query.filter(Run.test_id.in_(group_subquery))

    groupExcludeFilter = request.params.getall('exclude-group[]')
    if groupExcludeFilter:
        groupExc_subquery = DBSession.query(TestGroupMembership.test_id) \
            .filter(TestGroupMembership.group_id.in_(groupExcludeFilter))
        query = query.filter(~Run.test_id.in_(groupExc_subquery))

    classifierFilter = request.params.getall('select-classifier[]')
    if classifierFilter:
        subquery = DBSession.query(Run.id).join(TestRunClassification) \
            .filter(Run.job_id == job) \
            .filter(TestRunClassification.classifier_id.in_(classifierFilter))
        query = query.filter(Run.id.in_(subquery))

    classifierFilter = request.params.getall('exclude-classifier[]')
    if classifierFilter:
        subquery = DBSession.query(Run.id).join(TestRunClassification) \
            .filter(Run.job_id == job) \
            .filter(TestRunClassification.classifier_id.in_(classifierFilter))
        query = query.filter(~Run.id.in_(subquery))

    table = DataTable(request.GET, Run, query,
                      ["test_id", "stdout", "stderr", "result"])
    table.add_data(
        link=lambda o: request.route_url("view_test_run", test_id=o.id))
    # Search for similarity in Results or Regex in test_id
    table.searchable(lambda queryset, userinput: queryset.filter(or_(cast(Run.result, Text).\
                like('%' + userinput.upper() + '%'), Run.test_id.op('~')(userinput))))

    return table.json()
Exemple #26
0
 def get(self):
     """
     Render and return JSON response for GET /ajax/ofx
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(
         args, ScheduledTransaction, db_session.query(ScheduledTransaction),
         [
             'is_active',
             (
                 'amount',
                 lambda a: float(a.amount)
             ),
             'description',
             (
                 'account',
                 'account.name',
                 lambda i: "{} ({})".format(i.name, i.id)
             ),
             (
                 'budget',
                 'budget.name',
                 lambda i: "{} {}({})".format(
                     i.name,
                     '(income) ' if i.is_income else '',
                     i.id
                 )
             ),
             'recurrence_str',
             'schedule_type'
         ]
     )
     table.add_data(
         acct_id=lambda o: o.account_id,
         budget_id=lambda o: o.budget_id,
         id=lambda o: o.id
     )
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
 def get(self, project_id):
     """
     Render and return JSON response for
     GET /ajax/projects/<int:project_id>/bom_items
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(
         args, BoMItem,
         db_session.query(BoMItem).filter(
             BoMItem.project_id.__eq__(project_id)), [
                 'name', 'quantity', 'unit_cost', 'is_active', 'notes',
                 'url', 'id'
             ])
     table.add_data(line_cost=lambda o: float(o.unit_cost) * o.quantity)
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
def test_classifier(request):
    classifier = DBSession.query(TestClassifier) \
                          .filter_by(id=request.matchdict['classifier_id']) \
                          .first()

    col = getattr(Run, str(classifier.column))

    matched_runs = DBSession.query(Run.id, Run.test_id, col) \
                       .filter(col.op('~')(classifier.pattern))

    if request.params['job_id']:
        matched_runs = matched_runs.filter(Run.job_id == request.params['job_id'])

    table = DataTable(request.GET, Run, matched_runs, ["id", "test_id", classifier.column])
    table.add_data(link=lambda o: request.route_url("view_test_run", test_id=o.id))
    table.searchable(lambda queryset, userinput: queryset.filter(Run.test_id.op('~')(userinput)))
    return table.json()
Exemple #29
0
def test_classifier(request):
    classifier = DBSession.query(TestClassifier) \
                          .filter_by(id=request.matchdict['classifier_id']) \
                          .first()

    col = getattr(Run, str(classifier.column))

    matched_runs = DBSession.query(Run.id, Run.test_id, col) \
                       .filter(col.op('~')(classifier.pattern))

    if request.params['job_id']:
        matched_runs = matched_runs.filter(
            Run.job_id == request.params['job_id'])

    table = DataTable(request.GET, Run, matched_runs,
                      ["id", "test_id", classifier.column])
    table.add_data(
        link=lambda o: request.route_url("view_test_run", test_id=o.id))
    table.searchable(lambda queryset, userinput: queryset.filter(
        Run.test_id.op('~')(userinput)))
    return table.json()
def cheque_ajax(request):
    # database connection
    engine = create_engine(EARL)
    Session = sessionmaker(bind=engine)
    session = Session()
    # query
    #cheques = session.query(Cheque).order_by(desc(jbissue_date)).limit(length)
    #cheques = session.query(Cheque).order_by(desc(Cheque.jbissue_date))
    # datatable
    recci = request.GET
    status = 'I'
    if request.POST:
        status = request.POST.get('status')
        recci = request.POST
    cheques = session.query(Cheque).filter_by(jbstatus=status)
    table = DataTable(recci, Cheque, cheques, [
        'jbseqno',
        'jbchkno',
        'jbchknolnk',
        'jbstatus',
        'jbstatus_date',
        'jbimprt_date',
        'jbaccount',
        'jbamount',
        'jbamountlnk',
        'jbpayee'
    ])

    if not recci:
        return JsonResponse(
            {'message':"Missing GET/POST data for 'status' field"}, safe=False
        )
    else:
        table.add_data(link=lambda o: reverse_lazy('cheque_detail', args=[o.jbchkno]))
        table.add_data(pk=lambda o: o.jbchkno)
        #table.searchable(lambda queryset, user_input: cheque_search(queryset, user_input))
        session.close()
        jason = table.json()
        # DT_RowData dictionary contains a key named 'link', which is
        # a proxy object and JsonResponse() barfs on it, so we remove it
        for check in jason.get('data'):
            check.pop('DT_RowData', None)
        return JsonResponse(jason, safe=False)
def request_job_table(request):
    # Server side processing for DataTables plugin

    job = request.matchdict['job_id']
    query = DBSession.query(Run.id, Run.test_id, Run.stdout, Run.stderr, Run.result).filter(Run.job_id == job)

    resultFilter = request.params.getall('resultFilter[]')
    if resultFilter:
        query = query.filter(Run.result.in_(resultFilter))

    groupFilter = request.params.getall('select-group[]')
    if groupFilter:
        group_subquery = DBSession.query(TestGroupMembership.test_id) \
            .filter(TestGroupMembership.group_id.in_(groupFilter))
        query = query.filter(Run.test_id.in_(group_subquery))

    groupExcludeFilter = request.params.getall('exclude-group[]')
    if groupExcludeFilter:
        groupExc_subquery = DBSession.query(TestGroupMembership.test_id) \
            .filter(TestGroupMembership.group_id.in_(groupExcludeFilter))
        query = query.filter(~Run.test_id.in_(groupExc_subquery))

    classifierFilter = request.params.getall('select-classifier[]')
    if classifierFilter:
        subquery = DBSession.query(Run.id).join(TestRunClassification) \
            .filter(Run.job_id == job) \
            .filter(TestRunClassification.classifier_id.in_(classifierFilter))
        query = query.filter(Run.id.in_(subquery))

    classifierFilter = request.params.getall('exclude-classifier[]')
    if classifierFilter:
        subquery = DBSession.query(Run.id).join(TestRunClassification) \
            .filter(Run.job_id == job) \
            .filter(TestRunClassification.classifier_id.in_(classifierFilter))
        query = query.filter(~Run.id.in_(subquery))

    table = DataTable(request.GET, Run, query, ["test_id", "stdout", "stderr", "result"])
    table.add_data(link=lambda o: request.route_url("view_test_run", test_id=o.id))
    # Search for similarity in Results or Regex in test_id
    table.searchable(lambda queryset, userinput: queryset.filter(or_(cast(Run.result, Text).\
                like('%' + userinput.upper() + '%'), Run.test_id.op('~')(userinput))))

    return table.json()
Exemple #32
0
 def get(self):
     """
     Render and return JSON response for GET /ajax/ofx
     """
     args = request.args.to_dict()
     args_dict = self._args_dict(args)
     if self._have_column_search(args_dict) and args['search[value]'] == '':
         args['search[value]'] = 'FILTERHACK'
     table = DataTable(
         args, FuelFill,
         db_session.query(FuelFill).filter(
             FuelFill.vehicle.has(is_active=True)),
         [('date', lambda i: i.date.strftime('%Y-%m-%d')),
          ('vehicle', 'vehicle.name'), 'odometer_miles', 'reported_miles',
          'calculated_miles', 'level_before', 'level_after',
          'fill_location', 'cost_per_gallon', 'total_cost',
          ('gallons', lambda i: i.gallons.quantize(Decimal('.001'),
                                                   rounding=ROUND_FLOOR)),
          'reported_mpg', 'calculated_mpg', 'notes'])
     table.add_data(vehicle_id=lambda o: o.vehicle_id)
     if args['search[value]'] != '':
         table.searchable(lambda qs, s: self._filterhack(qs, s, args_dict))
     return jsonify(table.json())
Exemple #33
0
    def test_column_search(self):
        user, addr = self.make_user("Silly Sally", "Silly Sally Road")
        user2, addr2 = self.make_user("Silly Sall", "Silly Sally Roa")
        self.session.add_all((user, user2))
        self.session.commit()

        req = self.make_params(column_search={
            "name": {
                "value": "Silly Sally"
            }
        })

        table = DataTable(req, User, self.session.query(User), [("name", "full_name")])
        table.searchable_column(lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 1

        req = self.make_params(column_search={
            "name": {
                "value": "Silly Sall"
            }
        })

        table = DataTable(req, User, self.session.query(User), [("name", "full_name")])
        table.searchable_column(lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 2

        req = self.make_params(column_search={
            "name": {
                "value": "Silly Sall"
            },
            "address": {
                "value": "Silly Sally Road"
            }
        })

        table = DataTable(
            req,
            User, self.session.query(User),
            [("name", "full_name"), ("address", "address.description")]
        )
        table.searchable_column(lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 1
Exemple #34
0
def compare_table(request):
    # Server Side processing for Datatables.

    res = DBSession.query(Run.test_id, Run.id.label('run_id'), aliased_run.id.label('alt_id'), Run.result, aliased_run.result.label("alt_result")).\
                            join(aliased_run, Run.test_id == aliased_run.test_id).\
                            filter(Run.job_id == request.matchdict['job_id_source']).\
                            filter(aliased_run.job_id == request.matchdict['job_id_dest']).\
                            filter(aliased_run.result != Run.result)

    table = DataTable(request.GET, Run, res, [("test_id"), ("run_id"),
                                              ("alt_id"), ("result"),
                                              ("alt_result")])
    table.add_data(
        link=lambda o: request.route_url("view_test", test_id=o.test_id))
    table.add_data(sourcelink=lambda o: request.route_url("view_test_run",
                                                          test_id=o.run_id))
    table.add_data(destlink=lambda o: request.route_url("view_test_run",
                                                        test_id=o.alt_id))
    table.searchable(lambda queryset, userinput: queryset.\
            filter(Run.test_id.op('~')(userinput)))
    return table.json()
Exemple #35
0
    def test_column_search(self):
        user, addr = self.make_user("Silly Sally", "Silly Sally Road")
        user2, addr2 = self.make_user("Silly Sall", "Silly Sally Roa")
        self.session.add_all((user, user2))
        self.session.commit()

        req = self.make_params(
            column_search={"name": {
                "value": "Silly Sally"
            }})

        table = DataTable(req, User, self.session.query(User),
                          [("name", "full_name")])
        table.searchable_column(
            lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 1

        req = self.make_params(column_search={"name": {"value": "Silly Sall"}})

        table = DataTable(req, User, self.session.query(User),
                          [("name", "full_name")])
        table.searchable_column(
            lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 2

        req = self.make_params(
            column_search={
                "name": {
                    "value": "Silly Sall"
                },
                "address": {
                    "value": "Silly Sally Road"
                }
            })

        table = DataTable(req, User, self.session.query(User),
                          [("name", "full_name"),
                           ("address", "address.description")])
        table.searchable_column(
            lambda mc, qs, sq: qs.filter(mc.startswith(sq)))
        results = table.json()
        assert len(results["data"]) == 1