Esempio n. 1
0
def test_no_evaluate_recursive():

    def f(x):
        return x * 2

    subject = Struct(foo=f, bar=should_not_evaluate(f))
    assert 34 == evaluate_recursive(subject, x=17).foo
    assert 38 == evaluate_recursive(subject, x=17).bar(19)
Esempio n. 2
0
    def __init__(self, request=None, variables=None, variables_dict=None, endpoint_dispatch_prefix='query', **kwargs):  # variables=None to make pycharm tooling not confused
        """
        :type variables: list of Variable
        :type request: django.http.request.HttpRequest
        """
        self.endpoint_dispatch_prefix = endpoint_dispatch_prefix
        self.request = request
        self._form = None

        def generate_variables():
            if variables is not None:
                for variable in variables:
                    yield variable
            for name, variable in variables_dict.items():
                dict.__setitem__(variable, 'name', name)
                yield variable
        self.variables = sort_after(list(generate_variables()))

        def generate_bound_variables():
            for x in self.variables:
                yield BoundVariable(**merged(
                    Struct(x),
                    query=self,
                    attr=x.attr if x.attr is not MISSING else x.name
                ))
        bound_variables = list(generate_bound_variables())

        bound_variables = [evaluate_recursive(x, query=self, variable=x) for x in bound_variables]
        self.bound_variables = filter_show_recursive(bound_variables)

        self.bound_variable_by_name = {variable.name: variable for variable in self.bound_variables}

        self.gui_kwargs = extract_subkeys(kwargs, 'gui')
Esempio n. 3
0
 def __init__(self, table, row, **kwargs):
     """
     :type table: Table
     """
     self.table = table
     self.row = row
     super(BoundRow, self).__init__(**evaluate_recursive(kwargs, table=table, row=row))
Esempio n. 4
0
    def render_cell(self, bound_row):
        assert self.show

        row = bound_row.row
        value = self.cell_contents(bound_row=bound_row)

        table = bound_row.table
        if self.cell__template:
            cell_contents = render_to_string(self.cell__template, {'table': table, 'bound_column': self, 'bound_row': bound_row, 'row': bound_row.row, 'value': value})
        else:
            cell_contents = evaluate(self.cell__format, table=self.table, column=self, row=row, value=value)

            if self.cell__url:
                cell__url = self.cell__url(table=table, column=self, row=row, value=value) if callable(self.cell__url) else self.cell__url

                cell__url_title = self.cell__url_title(table=table, column=self, row=row, value=value) if callable(self.cell__url_title) else self.cell__url_title
                cell_contents = '<a href="{}"{}>{}</a>'.format(
                    cell__url,
                    ' title=%s' % cell__url_title if cell__url_title else '',
                    cell_contents,
                )

        return '<td{attrs}>{cell_contents}</td>'.format(
            attrs=render_attrs(evaluate_recursive(self.cell__attrs, table=table, column=self, row=row, value=value)),
            cell_contents=cell_contents,
        )
Esempio n. 5
0
 def bind_columns():
     for index, column in enumerate(self.columns):
         values = evaluate_recursive(Struct(column),
                                     table=self,
                                     column=column)
         values = merged(values, column=column, table=self, index=index)
         yield BoundColumn(**values)
Esempio n. 6
0
    def _prepare_evaluate_members(self):
        self.shown_bound_columns = [
            bound_column for bound_column in self.bound_columns
            if bound_column.show
        ]

        self.Meta = evaluate_recursive(self.Meta, table=self)

        if 'class' in self.Meta.attrs and isinstance(self.Meta.attrs['class'],
                                                     string_types):
            self.Meta.attrs['class'] = {
                k: True
                for k in self.Meta.attrs['class'].split(' ')
            }
        else:
            self.Meta.attrs['class'] = {}
        self.Meta.attrs.update(extract_subkeys(self.Meta, 'attrs'))
        self.Meta.attrs = collect_namespaces(self.Meta.attrs)

        if 'class' in self.Meta.row__attrs and isinstance(
                self.Meta.row__attrs['class'], string_types):
            self.Meta.row__attrs['class'] = {
                k: True
                for k in self.Meta.row__attrs['class'].split(' ')
            }
        else:
            self.Meta.row__attrs['class'] = {}
        self.Meta.row__attrs.update(extract_subkeys(self.Meta, 'row__attrs'))
        self.Meta.row__attrs = collect_namespaces(self.Meta.row__attrs)

        if not self.Meta.sortable:
            for bound_column in self.bound_columns:
                bound_column.sortable = False
Esempio n. 7
0
 def bind_columns():
     for index, column in enumerate(self.columns):
         values = evaluate_recursive(Struct(column), table=self, column=column)
         values = setdefaults_path(
             Struct(), self.column.get(column.name, {}), values, column=column, table=self, index=index
         )
         yield BoundColumn(**values)
Esempio n. 8
0
def test_evaluate_recursive():
    foo = {
        'foo': {'foo': lambda x: x * 2},
        'bar': [{'foo': lambda x: x * 2}],
        'baz': {lambda x: x * 2},
    }

    assert {'bar': [{'foo': 4}], 'foo': {'foo': 4}, 'baz': {4}} == evaluate_recursive(foo, x=2)
Esempio n. 9
0
    def __init__(self, table, row, row_index):
        self.table = table
        """ :type : Table """
        self.row = row
        """ :type : object """
        self.row_index = row_index

        args = Struct(evaluate_recursive(extract_subkeys(table.Meta, 'row'), table=table, row=row))
        self.template = args.template
        self.attrs = args.attrs
Esempio n. 10
0
 def evaluate(self):
     """
     Evaluates callable/lambda members. After this function is called all members will be values.
     """
     members_to_evaluate = {k: v for k, v in self.items() if k != 'post_validation'}
     for k, v in members_to_evaluate.items():
         self[k] = evaluate_recursive(v, form=self.form, field=self)
     if not self.editable:
         # noinspection PyAttributeOutsideInit
         self.input_template = 'tri_form/non_editable.html'
Esempio n. 11
0
 def evaluate(self):
     """
     Evaluates callable/lambda members. After this function is called all members will be values.
     """
     members_to_evaluate = {k: v for k, v in self.items() if k != 'post_validation'}
     for k, v in members_to_evaluate.items():
         self[k] = evaluate_recursive(v, form=self.form, field=self)
     if not self.editable:
         # noinspection PyAttributeOutsideInit
         self.input_template = 'tri_form/non_editable.html'
Esempio n. 12
0
    def _prepare_evaluate_members(self):
        self.shown_bound_columns = [bound_column for bound_column in self.bound_columns if bound_column.show]

        model = self.Meta.pop('model')  # avoid trying to eval model, since it's callable
        self.Meta = evaluate_recursive(self.Meta, table=self)
        self.Meta.model = model

        if not self.Meta.sortable:
            for bound_column in self.bound_columns:
                bound_column.sortable = False
Esempio n. 13
0
    def __init__(self, table, row, row_index):
        self.table = table
        """ :type : Table """
        self.row = row
        """ :type : object """
        self.row_index = row_index

        args = Struct(
            evaluate_recursive(extract_subkeys(table.Meta, 'row'),
                               table=table,
                               row=row))
        self.template = args.template
        self.attrs = args.attrs
Esempio n. 14
0
    def __init__(self, request=None, variables=None, **kwargs):  # variables=None to make pycharm tooling not confused
        """
        :type variables: list of Variable
        :type request: django.http.request.HttpRequest
        """
        self.request = request

        assert variables is not None
        if isinstance(variables, dict):  # Declarative case
            self.variables = [merged(variable, name=name) for name, variable in variables.items()]
        else:
            self.variables = variables

        bound_variables = [BoundVariable(**merged(Struct(x), query=self)) for x in self.variables]
        bound_variables = [evaluate_recursive(x, query=self, variable=x) for x in bound_variables]
        self.bound_variables = filter_show_recursive(bound_variables)

        self.bound_variable_by_name = {variable.name: variable for variable in self.bound_variables}

        self.gui_kwargs = extract_subkeys(kwargs, 'gui')
Esempio n. 15
0
def test_evaluate_recursive():
    foo = {
        'foo': {
            'foo': lambda x: x * 2
        },
        'bar': [{
            'foo': lambda x: x * 2
        }],
        'baz': {lambda x: x * 2},
        'boo': 17
    }

    assert {
        'bar': [{
            'foo': 4
        }],
        'foo': {
            'foo': 4
        },
        'baz': {4},
        'boo': 17
    } == evaluate_recursive(foo, x=2)
Esempio n. 16
0
    def _prepare_evaluate_members(self):
        self.shown_bound_columns = [bound_column for bound_column in self.bound_columns if bound_column.show]

        self.Meta = evaluate_recursive(self.Meta, table=self)

        if 'class' in self.Meta.attrs and isinstance(self.Meta.attrs['class'], basestring):
            self.Meta.attrs['class'] = {k: True for k in self.Meta.attrs['class'].split(' ')}
        else:
            self.Meta.attrs['class'] = {}
        self.Meta.attrs.update(extract_subkeys(self.Meta, 'attrs'))
        self.Meta.attrs = collect_namespaces(self.Meta.attrs)

        if 'class' in self.Meta.row__attrs and isinstance(self.Meta.row__attrs['class'], basestring):
            self.Meta.row__attrs['class'] = {k: True for k in self.Meta.row__attrs['class'].split(' ')}
        else:
            self.Meta.row__attrs['class'] = {}
        self.Meta.row__attrs.update(extract_subkeys(self.Meta, 'row__attrs'))
        self.Meta.row__attrs = collect_namespaces(self.Meta.row__attrs)

        if not self.Meta.sortable:
            for bound_column in self.bound_columns:
                bound_column.sortable = False
Esempio n. 17
0
    def _prepare_evaluate_members(self):
        self.shown_bound_columns = [bound_column for bound_column in self.bound_columns if bound_column.show]

        for attr in (
            "column",
            "bulk_filter",
            "bulk_exclude",
            "sortable",
            "attrs",
            "row",
            "filter",
            "header",
            "links",
            "model",
            "query",
            "bulk",
            "endpoint",
        ):
            setattr(self, attr, evaluate_recursive(getattr(self, attr), table=self))

        if not self.sortable:
            for bound_column in self.bound_columns:
                bound_column.sortable = False
Esempio n. 18
0
def table_context(request,
                  table,
                  links=None,
                  paginate_by=None,
                  page=None,
                  extra_context=None,
                  context_processors=None,
                  paginator=None,
                  show_hits=False,
                  hit_label='Items'):
    """
    :type table: Table
    """
    if extra_context is None:  # pragma: no cover
        extra_context = {}

    assert table.data is not None

    grouped_links = {}
    if links is not None:
        links = evaluate_recursive(links, table=table)
        links = [link for link in links if link.show and link.url]

        grouped_links = groupby(
            (link for link in links if link.group is not None),
            key=lambda l: l.group)
        grouped_links = [(g, slugify(g), list(lg)) for g, lg in grouped_links
                         ]  # because django templates are crap!

        links = [link for link in links if link.group is None]

    base_context = {
        'links': links,
        'grouped_links': grouped_links,
        'table': table,
    }

    if paginate_by:
        try:
            paginate_by = int(request.GET.get('page_size', paginate_by))
        except ValueError:  # pragma: no cover
            pass
        if paginator is None:
            paginator = Paginator(table.data, paginate_by)
            object_list = None
        else:  # pragma: no cover
            object_list = table.data
        if not page:
            page = request.GET.get('page', 1)
        try:
            page = int(page)
            if page < 1:  # pragma: no cover
                page = 1
            if page > paginator.num_pages:  # pragma: no cover
                page = paginator.num_pages
            if object_list is None:
                table.data = paginator.page(page).object_list
        except (InvalidPage, ValueError):  # pragma: no cover
            if page == 1:
                table.data = []
            else:
                raise Http404

        base_context.update({
            'request': request,
            'is_paginated': paginator.num_pages > 1,
            'results_per_page': paginate_by,
            'has_next': paginator.num_pages > page,
            'has_previous': page > 1,
            'page_size': paginate_by,
            'page': page,
            'next': page + 1,
            'previous': page - 1,
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'show_hits': show_hits,
            'hit_label': hit_label
        })
    else:  # pragma: no cover
        base_context.update({'is_paginated': False})

    base_context.update(extra_context)
    return RequestContext(request, base_context, context_processors)
Esempio n. 19
0
 def attrs(self):
     return evaluate_recursive(self.bound_column.cell.attrs,
                               table=self.table,
                               column=self.bound_column,
                               row=self.row,
                               value=self.value)
Esempio n. 20
0
 def attrs(self):
     return evaluate_recursive(
         self.bound_column.cell.attrs, table=self.table, column=self.bound_column, row=self.row, value=self.value
     )
Esempio n. 21
0
def table_context(
    request,
    table,
    links=None,
    paginate_by=None,
    page=None,
    extra_context=None,
    context_processors=None,
    paginator=None,
    show_hits=False,
    hit_label="Items",
):
    """
    :type table: Table
    """
    if extra_context is None:  # pragma: no cover
        extra_context = {}

    assert table.data is not None

    grouped_links = {}
    if links is not None:
        links = evaluate_recursive(links, table=table)
        links = [link for link in links if link.show and link.url]

        grouped_links = groupby((link for link in links if link.group is not None), key=lambda l: l.group)
        grouped_links = [(g, slugify(g), list(lg)) for g, lg in grouped_links]  # because django templates are crap!

        links = [link for link in links if link.group is None]

    base_context = {"links": links, "grouped_links": grouped_links, "table": table}

    if paginate_by:
        try:
            paginate_by = int(request.GET.get("page_size", paginate_by))
        except ValueError:  # pragma: no cover
            pass
        if paginator is None:
            paginator = Paginator(table.data, paginate_by)
            object_list = None
        else:  # pragma: no cover
            object_list = table.data
        if not page:
            page = request.GET.get("page", 1)
        try:
            page = int(page)
            if page < 1:  # pragma: no cover
                page = 1
            if page > paginator.num_pages:  # pragma: no cover
                page = paginator.num_pages
            if object_list is None:
                table.data = paginator.page(page).object_list
        except (InvalidPage, ValueError):  # pragma: no cover
            if page == 1:
                table.data = []
            else:
                raise Http404

        base_context.update(
            {
                "request": request,
                "is_paginated": paginator.num_pages > 1,
                "results_per_page": paginate_by,
                "has_next": paginator.num_pages > page,
                "has_previous": page > 1,
                "page_size": paginate_by,
                "page": page,
                "next": page + 1,
                "previous": page - 1,
                "pages": paginator.num_pages,
                "hits": paginator.count,
                "show_hits": show_hits,
                "hit_label": hit_label,
            }
        )
    else:  # pragma: no cover
        base_context.update({"is_paginated": False})

    base_context.update(extra_context)
    return RequestContext(request, base_context, context_processors)
Esempio n. 22
0
 def __iter__(self):
     self.prepare(self.request)
     for i, row in enumerate(self.data):
         yield BoundRow(table=self, row=row, row_index=i, **evaluate_recursive(self.row, table=self, row=row))
Esempio n. 23
0
def table_context(request,
                  table,
                  links=None,
                  paginate_by=None,
                  page=None,
                  extra_context=None,
                  context_processors=None,
                  paginator=None,
                  show_hits=False,
                  hit_label='Items'):
    """
    :type table: Table
    """
    if extra_context is None:  # pragma: no cover
        extra_context = {}

    grouped_links = {}
    if links is not None:
        links = evaluate_recursive(links, table=table)
        links = [link for link in links if link.show and link.url]

        grouped_links = groupby((link for link in links if link.group is not None), key=lambda l: l.group)
        grouped_links = [(g, slugify(g), list(lg)) for g, lg in grouped_links]  # because django templates are crap!

        links = [link for link in links if link.group is None]

    base_context = {
        'links': links,
        'grouped_links': grouped_links,
        'table': table,
    }

    if paginate_by:
        try:
            paginate_by = int(request.GET.get('page_size', paginate_by))
        except ValueError:  # pragma: no cover
            pass
        if paginator is None:
            paginator = Paginator(table.data, paginate_by)
            object_list = None
        else:  # pragma: no cover
            object_list = table.data
        if not page:
            page = request.GET.get('page', 1)
        try:
            page = int(page)
            if page < 1:  # pragma: no cover
                page = 1
            if page > paginator.num_pages:  # pragma: no cover
                page = paginator.num_pages
            if object_list is None:
                table.data = paginator.page(page).object_list
        except (InvalidPage, ValueError):  # pragma: no cover
            if page == 1:
                table.data = []
            else:
                raise Http404

        base_context.update({
            'request': request,
            'is_paginated': paginator.num_pages > 1,
            'results_per_page': paginate_by,
            'has_next': paginator.num_pages > page,
            'has_previous': page > 1,
            'page_size': paginate_by,
            'page': page,
            'next': page + 1,
            'previous': page - 1,
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'show_hits': show_hits,
            'hit_label': hit_label})
    else:  # pragma: no cover
        base_context.update({
            'is_paginated': False})

    base_context.update(extra_context)
    return RequestContext(request, base_context, context_processors)
Esempio n. 24
0
 def bind_columns():
     for index, column in enumerate(self.columns):
         values = evaluate_recursive(Struct(column), table=self, column=column)
         values = merged(values, column=column, table=self, index=index)
         yield BoundColumn(**values)
Esempio n. 25
0
 def render_attrs(self):
     attrs = evaluate_recursive(self.bound_column.cell.attrs, table=self.table, column=self.bound_column, row=self.row, value=self.value)
     return render_attrs(attrs)