コード例 #1
0
def test_no_evaluate():

    def f(x):
        return x * 2

    assert 34 == evaluate(f, x=17)
    assert 34 == should_not_evaluate(f)(17)
    assert 38 == evaluate(should_not_evaluate(f), x=42)(19)
    assert 38 == force_evaluate(should_not_evaluate(f), x=19)
    assert 19 == should_not_evaluate(19)  # should_not_evaluate() on a non-callable is a no-op
    assert 19 == should_evaluate(19)  # should_evaluate() on a non-callable is a no-op
    assert 46 == evaluate(should_evaluate(should_not_evaluate(f)), x=23)
コード例 #2
0
def test_evaluate_on_methods():
    class Foo(object):
        def bar(self, x):
            return x

        @staticmethod
        def baz(x):
            return x

    assert 17 == evaluate(Foo().bar, x=17)
    assert 17 == evaluate(Foo().baz, x=17)

    f = Foo().bar
    assert f is evaluate(f, y=17)
コード例 #3
0
ファイル: __init__.py プロジェクト: pombredanne/tri.table
    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,
        )
コード例 #4
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
    def select(is_report=False,
               checkbox_name='pk',
               show=True,
               checked=lambda x: False,
               **kwargs):
        """
        Shortcut for a column of checkboxes to select rows. This is useful for implementing bulk operations.

        :param checkbox_name: the name of the checkbox. Default is "pk", resulting in checkboxes like "pk_1234".
        :param checked: callable to specify if the checkbox should be checked initially. Defaults to False.
        """
        setdefaults(
            kwargs,
            dict(
                name='__select__',
                title='Select all',
                display_name=mark_safe('<i class="fa fa-check-square-o"></i>'),
                sortable=False,
                show=lambda table, column: evaluate(
                    show, table=table, column=column) and not is_report,
                attrs__class__thin=True,
                attrs__class__nopad=True,
                cell__attrs__class__cj=True,
                cell__value=lambda table, column, row: mark_safe(
                    '<input type="checkbox"%s class="checkbox" name="%s_%s" />'
                    % (' checked'
                       if checked(row.pk) else '', checkbox_name, row.pk)),
            ))
        return Column(**kwargs)
コード例 #5
0
ファイル: __init__.py プロジェクト: TriOptima/tri.table
    def select(is_report=False, checkbox_name="pk", show=True, checked=lambda x: False, **kwargs):
        """
        Shortcut for a column of checkboxes to select rows. This is useful for implementing bulk operations.

        :param checkbox_name: the name of the checkbox. Default is "pk", resulting in checkboxes like "pk_1234".
        :param checked: callable to specify if the checkbox should be checked initially. Defaults to False.
        """
        setdefaults(
            kwargs,
            dict(
                name="__select__",
                title="Select all",
                display_name=mark_safe('<i class="fa fa-check-square-o"></i>'),
                sortable=False,
                show=lambda table, **rest: evaluate(show, table=table, **rest) and not is_report,
                attrs__class__thin=True,
                attrs__class__nopad=True,
                cell__attrs__class__cj=True,
                cell__value=lambda row, **_: mark_safe(
                    '<input type="checkbox"%s class="checkbox" name="%s_%s" />'
                    % (" checked" if checked(row.pk) else "", checkbox_name, row.pk)
                ),
            ),
        )
        return Column(**kwargs)
コード例 #6
0
ファイル: __init__.py プロジェクト: TriOptima/tri.table
    def _prepare_sorting(self):
        # sorting
        order = self.request.GET.get("order", None)
        if order is not None:
            is_desc = order[0] == "-"
            order_field = is_desc and order[1:] or order
            tmp = [x for x in self.shown_bound_columns if x.name == order_field]
            if len(tmp) == 0:
                return  # Unidentified sort column
            sort_column = tmp[0]
            order_args = evaluate(sort_column.sort_key, column=sort_column)
            order_args = isinstance(order_args, list) and order_args or [order_args]

            if sort_column.sortable:
                if isinstance(self.data, list):
                    order_by_on_list(self.data, order_args[0], is_desc)
                else:
                    if not settings.DEBUG:
                        # We should crash on invalid sort commands in DEV, but just ignore in PROD
                        # noinspection PyProtectedMember
                        valid_sort_fields = {x.name for x in self.model._meta.fields}
                        order_args = [
                            order_arg for order_arg in order_args if order_arg.split("__", 1)[0] in valid_sort_fields
                        ]
                    order_args = ["%s%s" % (is_desc and "-" or "", x) for x in order_args]
                    self.data = self.data.order_by(*order_args)
コード例 #7
0
def delete(request, model, pk, title):
    return delete_object(
        request=request,
        model=model,
        instance=get_object_or_404(model, pk=pk),
        render__context__title=evaluate(title, model=model),
    )
コード例 #8
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
    def _prepare_sorting(self):
        # sorting
        order = self.request.GET.get('order', None)
        if order is not None:
            is_desc = order[0] == '-'
            order_field = is_desc and order[1:] or order
            sort_column = [
                x for x in self.shown_bound_columns if x.name == order_field
            ][0]
            order_args = evaluate(sort_column.sort_key, column=sort_column)
            order_args = isinstance(order_args, list) and order_args or [
                order_args
            ]

            if sort_column.sortable:
                if isinstance(self.data, list):
                    order_by_on_list(self.data, order_args[0], is_desc)
                else:
                    if not settings.DEBUG:
                        # We should crash on invalid sort commands in DEV, but just ignore in PROD
                        # noinspection PyProtectedMember
                        valid_sort_fields = {
                            x.name
                            for x in self.Meta.model._meta.fields
                        }
                        order_args = [
                            order_arg for order_arg in order_args
                            if order_arg.split('__', 1)[0] in valid_sort_fields
                        ]
                    order_args = [
                        "%s%s" % (is_desc and '-' or '', x) for x in order_args
                    ]
                    self.data = self.data.order_by(*order_args)
コード例 #9
0
ファイル: __init__.py プロジェクト: TriOptima/tri.table
    def icon(icon, is_report=False, icon_title="", show=True, **kwargs):
        """
        Shortcut to create font awesome-style icons.

        :param icon: the font awesome name of the icon
        """
        setdefaults(
            kwargs,
            dict(
                name="",
                display_name="",
                sortable=False,
                attrs__class__thin=True,
                show=lambda table, **rest: evaluate(show, table=table, **rest) and not is_report,
                title=icon_title,
                cell__value=lambda table, column, row, **_: True,
                cell__attrs__class__cj=True,
                cell__format=lambda value, **_: mark_safe(
                    '<i class="fa fa-lg fa-%s"%s></i>' % (icon, ' title="%s"' % icon_title if icon_title else "")
                )
                if value
                else "",
            ),
        )
        return Column(**kwargs)
コード例 #10
0
ファイル: __init__.py プロジェクト: timb07/mutmut
def mutate_node(i, context):
    if not i:
        return

    context.stack.append(i)
    try:

        t = i['type']

        if t == 'endl':
            context.current_line += 1

        assert t in mutations_by_type, (t, i.keys(), dumps(i))
        m = mutations_by_type[t]

        if 'replace_entire_node_with' in m:
            if context.exclude_line():
                return

            if context.mutate_index in (ALL, context.index):
                i.clear()
                for k, v in m['replace_entire_node_with'].items():
                    i[k] = v
                context.performed_mutations += 1
            context.index += 1
            return

        for _, x in sorted(i.items()):
            if x is None:
                continue  # pragma: no cover

            if isinstance(x, list):
                if x:
                    mutate_list_of_nodes(x, context=context)
            elif isinstance(x, dict):
                mutate_node(x, context=context)
            else:
                assert isinstance(x, text_types + (bool, ))

            if context.performed_mutations and context.mutate_index != ALL:
                return

        for key, value in sorted(m.items()):
            old = i[key]
            if context.exclude_line():
                continue

            new = evaluate(value, context=context, node=i, **i)
            assert not callable(new)
            if new != old:
                if context.mutate_index in (ALL, context.index):
                    context.performed_mutations += 1
                    i[key] = new
                context.index += 1

            if context.performed_mutations and context.mutate_index != ALL:
                return
    finally:
        context.stack.pop()
コード例 #11
0
def view(request, model, pk, title):
    return edit_object(
        request=request,
        instance=get_object_or_404(model, pk=pk),
        form__editable=False,
        form__links=[],
        render__context__title=evaluate(title, model=model),
    )
コード例 #12
0
ファイル: __init__.py プロジェクト: pombredanne/tri.form
 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(v, form=self.form, field=self)
     if not self.editable:
         # noinspection PyAttributeOutsideInit
         self.input_template = 'tri_form/non_editable.html'
コード例 #13
0
ファイル: __init__.py プロジェクト: azureatom/tri.table
    def __init__(self, bound_row, bound_column):

        assert bound_column.show

        self.bound_column = bound_column
        self.bound_row = bound_row
        self.table = bound_row.table
        self.row = bound_row.row

        self.value = evaluate(bound_column.cell.value, table=bound_row.table, column=bound_column.column, row=bound_row.row)
コード例 #14
0
def mutate_node(i, context):
    """
    :type context: Context
    """
    if not i:
        return

    context.stack.append(i)
    try:

        t = i.type

        # import pytest; pytest.set_trace()

        if i.start_pos[0] - 1 != context.current_line_index:
            context.current_line_index = i.start_pos[0] - 1
            context.index = 0  # indexes are unique per line, so start over here!

        m = mutations_by_type.get(t, {})

        if hasattr(i, 'children'):
            mutate_list_of_nodes(i, context=context)

            # this is just an optimization to stop early
            if context.number_of_performed_mutations and context.mutate_id != ALL:
                return

        if m == {}:
            return

        for key, value in sorted(m.items()):
            old = getattr(i, key)
            if context.exclude_line():
                continue

            new = evaluate(
                value,
                context=context,
                node=i,
                value=getattr(i, 'value', None),
                children=getattr(i, 'children', None),
            )
            assert not callable(new)
            if new != old:
                if context.should_mutate():
                    context.number_of_performed_mutations += 1
                    context.performed_mutation_ids.append(context.mutate_id_of_current_index)
                    setattr(i, key, new)
                context.index += 1

            # this is just an optimization to stop early
            if context.number_of_performed_mutations and context.mutate_id != ALL:
                return
    finally:
        context.stack.pop()
コード例 #15
0
ファイル: views.py プロジェクト: boxed/mammon
        def inline_edit_select_cell_format(table, column, row, value):
            options = '<option value=""></option>' + "\n".join(
                [
                    '<option value="%s"%s>%s</option>'
                    % (choice.pk, ' selected="selected"' if choice == value else "", choice)
                    for choice in evaluate(kwargs["choices"], table=table, column=column, row=row, value=value)
                ]
            )

            return mark_safe(
                '<select class="inline_editable_select" edit_url="%sedit/%s/" id="%s">%s</select>'
                % (row.get_absolute_url(), column.name, row.pk, options)
            )
コード例 #16
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
    def __init__(self, bound_row, bound_column):

        assert bound_column.show

        self.bound_column = bound_column
        self.bound_row = bound_row
        self.table = bound_row.table
        self.row = bound_row.row

        self.value = evaluate(bound_column.cell.value,
                              table=bound_row.table,
                              column=bound_column.column,
                              row=bound_row.row)
コード例 #17
0
ファイル: __init__.py プロジェクト: neroks/mutmut
def mutate_node(node, context):
    """
    :type context: Context
    """
    context.stack.append(node)
    try:
        if node.type in ('tfpdef', 'import_from', 'import_name'):
            return

        if node.start_pos[0] - 1 != context.current_line_index:
            context.current_line_index = node.start_pos[0] - 1
            context.index = 0  # indexes are unique per line, so start over here!

        if hasattr(node, 'children'):
            mutate_list_of_nodes(node, context=context)

            # this is just an optimization to stop early
            if context.number_of_performed_mutations and context.mutation_id != ALL:
                return

        mutation = mutations_by_type.get(node.type)

        if mutation is None:
            return

        for key, value in sorted(mutation.items()):
            old = getattr(node, key)
            if context.exclude_line():
                continue

            new = evaluate(
                value,
                context=context,
                node=node,
                value=getattr(node, 'value', None),
                children=getattr(node, 'children', None),
            )
            assert not callable(new)
            if new is not None and new != old:
                if context.should_mutate():
                    context.number_of_performed_mutations += 1
                    context.performed_mutation_ids.append(
                        context.mutation_id_of_current_index)
                    setattr(node, key, new)
                context.index += 1

            # this is just an optimization to stop early
            if context.number_of_performed_mutations and context.mutation_id != ALL:
                return
    finally:
        context.stack.pop()
コード例 #18
0
ファイル: __init__.py プロジェクト: pombredanne/tri.table
 def run(is_report=False, show=True, **kwargs):
     """
     Shortcut for creating a clickable run icon. The URL defaults to `your_object.get_absolute_url() + 'run/'`. Specify the option cell__url to override.
     """
     setdefaults(kwargs, dict(
         name='',
         title='Run',
         sortable=False,
         css_class={'thin'},
         cell__url=lambda row, **_: row.get_absolute_url() + 'run/',
         cell__value='Run',
         show=lambda table, column: evaluate(show, table=table, column=column) and not is_report,
     ))
     return Column(**kwargs)
コード例 #19
0
        def inline_edit_select_cell_format(table, column, row, value):
            options = '<option value=""></option>' + '\n'.join([
                '<option value="%s"%s>%s</option>' %
                (choice.pk, ' selected="selected"' if choice == value else '',
                 choice) for choice in evaluate(kwargs['choices'],
                                                table=table,
                                                column=column,
                                                row=row,
                                                value=value)
            ])

            return mark_safe(
                '<select class="inline_editable_select" edit_url="%sedit/%s/" id="%s">%s</select>'
                % (row.get_absolute_url(), column.name, row.pk, options))
コード例 #20
0
ファイル: __init__.py プロジェクト: azureatom/tri.table
    def __init__(self, **kwargs):
        """
        :param name: the name of the column
        :param attr: What attribute to use, defaults to same as name. Follows django conventions to access properties of properties, so "foo__bar" is equivalent to the python code `foo.bar`. This parameter is based on the variable name of the Column if you use the declarative style of creating tables.
        :param display_name: the text of the header for this column. By default this is based on the `name` parameter so normally you won't need to specify it.
        :param css_class: CSS class of the header
        :param url: URL of the header. This should only be used if "sorting" is off.
        :param title: title/tool tip of header
        :param show: set this to False to hide the column
        :param sortable: set this to False to disable sorting on this column
        :param sort_key: string denoting what value to use as sort key when this column is selected for sorting. (Or callable when rendering a table from list.)
        :param sort_default_desc: Set to True to make table sort link to sort descending first.
        :param group: string describing the group of the header. If this parameter is used the header of the table now has two rows. Consecutive identical groups on the first level of the header are joined in a nice way.
        :param auto_rowspan: enable automatic rowspan for this column. To join two cells with rowspan, just set this auto_rowspan to True and make those two cells output the same text and we'll handle the rest.
        :param cell__template: name of a template file. The template gets arguments: `table`, `bound_column`, `bound_row`, `row` and `value`.
        :param cell__value: string or callable that receives kw arguments: `table`, `column` and `row`. This is used to extract which data to display from the object.
        :param cell__format: string or callable that receives kw arguments: `table`, `column`, `row` and `value`. This is used to convert the extracted data to html output (use `mark_safe`) or a string.
        :param cell__attrs: dict of attr name to callables that receive kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url_title: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        """

        kwargs.update({'attrs__class__' + c: True for c in kwargs.get('css_class', {})})

        setdefaults(kwargs, dict(
            bulk__show=False,
            query__show=False,
            extra=Struct(),
            attrs={},
            cell__template=None,
            cell__value=lambda table, column, row: getattr_path(row, evaluate(column.attr, table=table, column=column)),
            cell__format=default_cell_formatter,
            cell__attrs={},
            cell__url=None,
            cell__url_title=None
        ))
        namespaces = Struct(collect_namespaces(kwargs))
        namespaces.attrs = Struct(collect_namespaces(namespaces.attrs))
        namespaces.cell = Struct(collect_namespaces(namespaces.cell))
        namespaces.cell.attrs = Struct(collect_namespaces(namespaces.cell.attrs))

        namespaces.bulk = Struct(namespaces.bulk)
        namespaces.query = Struct(namespaces.query)
        namespaces.extra = Struct(namespaces.extra)

        setdefaults(namespaces.attrs, {'class': {}})
        setdefaults(namespaces.cell.attrs, {'class': {}})

        super(Column, self).__init__(**namespaces)
コード例 #21
0
def list(request, model, title):
    return render_table_to_response(
        request=request,
        table__model=model,
        table__column__name__cell__url=lambda row, **_: f'{row.pk}/',
        table__extra_fields=[
            Column.edit(after=0, cell__url=lambda row, **_: f'{row.pk}/edit/'),
            Column.delete(after=0,
                          cell__url=lambda row, **_: f'{row.pk}/delete/'),
        ],
        template='wiki/list.html',
        context=dict(title=evaluate(title, model=model), ),
        links=[
            Link(f'Create {model._meta.verbose_name}', attrs__href='create/')
        ])
コード例 #22
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
 def run(is_report=False, show=True, **kwargs):
     """
     Shortcut for creating a clickable run icon. The URL defaults to `your_object.get_absolute_url() + 'run/'`. Specify the option cell__url to override.
     """
     setdefaults(
         kwargs,
         dict(
             name='',
             title='Run',
             sortable=False,
             css_class={'thin'},
             cell__url=lambda row, **_: row.get_absolute_url() + 'run/',
             cell__value='Run',
             show=lambda table, column: evaluate(
                 show, table=table, column=column) and not is_report,
         ))
     return Column(**kwargs)
コード例 #23
0
ファイル: __init__.py プロジェクト: pombredanne/tri.table
    def select(is_report=False, checkbox_name='pk', show=True, checked=lambda x: False, **kwargs):
        """
        Shortcut for a column of checkboxes to select rows. This is useful for implementing bulk operations.

        :param checkbox_name: the name of the checkbox. Default is "pk", resulting in checkboxes like "pk_1234".
        :param checked: callable to specify if the checkbox should be checked initially. Defaults to False.
        """
        setdefaults(kwargs, dict(
            name='__select__',
            title='Select all',
            display_name=mark_safe('<i class="fa fa-check-square-o"></i>'),
            sortable=False,
            show=lambda table, column: evaluate(show, table=table, column=column) and not is_report,
            css_class={'thin', 'nopad'},
            cell__attrs={'class': 'cj'},
            cell__value=lambda table, column, row: mark_safe('<input type="checkbox"%s class="checkbox" name="%s_%s" />' % (' checked' if checked(row.pk) else '', checkbox_name, row.pk)),
        ))
        return Column(**kwargs)
コード例 #24
0
ファイル: __init__.py プロジェクト: pombredanne/tri.table
    def icon(icon, is_report=False, icon_title='', show=True, **kwargs):
        """
        Shortcut to create font awesome-style icons.

        :param icon: the font awesome name of the icon
        """
        setdefaults(kwargs, dict(
            name='',
            display_name='',
            sortable=False,
            css_class={'thin'},
            show=lambda table, column: evaluate(show, table=table, column=column) and not is_report,
            title=icon_title,
            cell__value=lambda table, column, row: True,
            cell__attrs={'class': 'cj'},
            cell__format=lambda table, column, row, value: mark_safe('<i class="fa fa-lg fa-%s"%s></i>' % (icon, ' title="%s"' % icon_title if icon_title else '')) if value else ''
        ))
        return Column(**kwargs)
コード例 #25
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
    def icon(icon, is_report=False, icon_title='', show=True, **kwargs):
        """
        Shortcut to create font awesome-style icons.

        :param icon: the font awesome name of the icon
        """
        setdefaults(
            kwargs,
            dict(name='',
                 display_name='',
                 sortable=False,
                 attrs__class__thin=True,
                 show=lambda table, column: evaluate(
                     show, table=table, column=column) and not is_report,
                 title=icon_title,
                 cell__value=lambda table, column, row: True,
                 cell__attrs__class__cj=True,
                 cell__format=lambda table, column, row, value:
                 mark_safe('<i class="fa fa-lg fa-%s"%s></i>' %
                           (icon, ' title="%s"' % icon_title
                            if icon_title else '')) if value else ''))
        return Column(**kwargs)
コード例 #26
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
class Column(Frozen, ColumnBase):
    @dispatch(
        bulk__show=False,
        query__show=False,
        attrs=EMPTY,
        attrs__class=EMPTY,
        cell__template=None,
        cell__attrs=EMPTY,
        cell__value=lambda table, column, row: getattr_path(
            row, evaluate(column.attr, table=table, column=column)),
        cell__format=default_cell_formatter,
        cell__url=None,
        cell__url_title=None,
    )
    def __init__(self, **kwargs):
        """
        :param name: the name of the column
        :param attr: What attribute to use, defaults to same as name. Follows django conventions to access properties of properties, so "foo__bar" is equivalent to the python code `foo.bar`. This parameter is based on the variable name of the Column if you use the declarative style of creating tables.
        :param display_name: the text of the header for this column. By default this is based on the `name` parameter so normally you won't need to specify it.
        :param css_class: CSS class of the header
        :param url: URL of the header. This should only be used if "sorting" is off.
        :param title: title/tool tip of header
        :param show: set this to False to hide the column
        :param sortable: set this to False to disable sorting on this column
        :param sort_key: string denoting what value to use as sort key when this column is selected for sorting. (Or callable when rendering a table from list.)
        :param sort_default_desc: Set to True to make table sort link to sort descending first.
        :param group: string describing the group of the header. If this parameter is used the header of the table now has two rows. Consecutive identical groups on the first level of the header are joined in a nice way.
        :param auto_rowspan: enable automatic rowspan for this column. To join two cells with rowspan, just set this auto_rowspan to True and make those two cells output the same text and we'll handle the rest.
        :param cell__template: name of a template file. The template gets arguments: `table`, `bound_column`, `bound_row`, `row` and `value`.
        :param cell__value: string or callable that receives kw arguments: `table`, `column` and `row`. This is used to extract which data to display from the object.
        :param cell__format: string or callable that receives kw arguments: `table`, `column`, `row` and `value`. This is used to convert the extracted data to html output (use `mark_safe`) or a string.
        :param cell__attrs: dict of attr name to callables that receive kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        :param cell__url_title: callable that receives kw arguments: `table`, `column`, `row` and `value`.
        """

        setdefaults_path(
            kwargs,
            {'attrs__class__' + c: True
             for c in kwargs.get('css_class', {})})
        super(Column, self).__init__(**kwargs)

    @staticmethod
    def text(**kwargs):
        return Column(**kwargs)

    @staticmethod
    def icon(icon, is_report=False, icon_title='', show=True, **kwargs):
        """
        Shortcut to create font awesome-style icons.

        :param icon: the font awesome name of the icon
        """
        setdefaults(
            kwargs,
            dict(name='',
                 display_name='',
                 sortable=False,
                 attrs__class__thin=True,
                 show=lambda table, column: evaluate(
                     show, table=table, column=column) and not is_report,
                 title=icon_title,
                 cell__value=lambda table, column, row: True,
                 cell__attrs__class__cj=True,
                 cell__format=lambda table, column, row, value:
                 mark_safe('<i class="fa fa-lg fa-%s"%s></i>' %
                           (icon, ' title="%s"' % icon_title
                            if icon_title else '')) if value else ''))
        return Column(**kwargs)

    @staticmethod
    def edit(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable edit icon. The URL defaults to `your_object.get_absolute_url() + 'edit/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(cell__url=lambda row, **_: row.get_absolute_url() + 'edit/',
                 display_name=''))
        return Column.icon('pencil-square-o', is_report, 'Edit', **kwargs)

    @staticmethod
    def delete(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable delete icon. The URL defaults to `your_object.get_absolute_url() + 'delete/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(cell__url=lambda row, **_: row.get_absolute_url() + 'delete/',
                 display_name=''))
        return Column.icon('trash-o', is_report, 'Delete', **kwargs)

    @staticmethod
    def download(is_report=False, **kwargs):
        """
        Shortcut for creating a clickable download icon. The URL defaults to `your_object.get_absolute_url() + 'download/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(
                cell__url=lambda row, **_: row.get_absolute_url() +
                'download/',
                cell__value=lambda row, **_: getattr(row, 'pk', False),
            ))
        return Column.icon('download', is_report, 'Download', **kwargs)

    @staticmethod
    def run(is_report=False, show=True, **kwargs):
        """
        Shortcut for creating a clickable run icon. The URL defaults to `your_object.get_absolute_url() + 'run/'`. Specify the option cell__url to override.
        """
        setdefaults(
            kwargs,
            dict(
                name='',
                title='Run',
                sortable=False,
                css_class={'thin'},
                cell__url=lambda row, **_: row.get_absolute_url() + 'run/',
                cell__value='Run',
                show=lambda table, column: evaluate(
                    show, table=table, column=column) and not is_report,
            ))
        return Column(**kwargs)

    @staticmethod
    def select(is_report=False,
               checkbox_name='pk',
               show=True,
               checked=lambda x: False,
               **kwargs):
        """
        Shortcut for a column of checkboxes to select rows. This is useful for implementing bulk operations.

        :param checkbox_name: the name of the checkbox. Default is "pk", resulting in checkboxes like "pk_1234".
        :param checked: callable to specify if the checkbox should be checked initially. Defaults to False.
        """
        setdefaults(
            kwargs,
            dict(
                name='__select__',
                title='Select all',
                display_name=mark_safe('<i class="fa fa-check-square-o"></i>'),
                sortable=False,
                show=lambda table, column: evaluate(
                    show, table=table, column=column) and not is_report,
                attrs__class__thin=True,
                attrs__class__nopad=True,
                cell__attrs__class__cj=True,
                cell__value=lambda table, column, row: mark_safe(
                    '<input type="checkbox"%s class="checkbox" name="%s_%s" />'
                    % (' checked'
                       if checked(row.pk) else '', checkbox_name, row.pk)),
            ))
        return Column(**kwargs)

    @staticmethod
    def boolean(is_report=False, **kwargs):
        """
        Shortcut to render booleans as a check mark if true or blank if false.
        """
        def render_icon(value):
            if callable(value):
                value = value()
            return mark_safe(
                '<i class="fa fa-check" title="Yes"></i>') if value else ''

        setdefaults(
            kwargs,
            dict(
                cell__format=lambda table, column, row, value:
                yes_no_formatter(
                    table=table, column=column, row=row, value=value)
                if is_report else render_icon(value),
                cell__attrs__class__cj=True,
                query__class=Variable.boolean,
                bulk__class=Field.boolean,
            ))
        return Column(**kwargs)

    @staticmethod
    def link(**kwargs):
        """
        Shortcut for creating a cell that is a link. The URL is the result of calling `get_absolute_url()` on the object.
        """
        def url(table, column, row, value):
            del table, value
            r = getattr_path(row, column.attr)
            return r.get_absolute_url() if r else ''

        setdefaults(kwargs, dict(cell__url=url, ))
        return Column(**kwargs)

    @staticmethod
    def number(**kwargs):
        """
        Shortcut for rendering a number. Sets the "rj" (as in "right justified") CSS class on the cell and header.
        """
        setdefaults(kwargs, dict(cell__attrs__class__rj=True))
        return Column(**kwargs)

    @staticmethod
    def float(**kwargs):
        return Column.number(**kwargs)

    @staticmethod
    def integer(**kwargs):
        return Column.number(**kwargs)

    @staticmethod
    def choice_queryset(**kwargs):
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.choice_queryset,
                bulk__model=kwargs.get('model'),
                query__class=Variable.choice_queryset,
                query__model=kwargs.get('model'),
            ))
        return Column.choice(**kwargs)

    @staticmethod
    def multi_choice_queryset(**kwargs):
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.multi_choice_queryset,
                bulk__model=kwargs.get('model'),
                query__class=Variable.multi_choice_queryset,
                query__model=kwargs.get('model'),
                cell__format=lambda value, **_: ', '.join(
                    ['%s' % x for x in value.all()]),
            ))
        return Column.choice(**kwargs)

    @staticmethod
    def choice(**kwargs):
        choices = kwargs['choices']
        setdefaults(
            kwargs,
            dict(
                bulk__class=Field.choice,
                bulk__choices=choices,
                query__class=Variable.choice,
                query__choices=choices,
            ))
        return Column(**kwargs)

    @staticmethod
    def substring(**kwargs):
        setdefaults(kwargs, dict(query__gui_op=':', ))
        return Column(**kwargs)

    @staticmethod
    def date(**kwargs):
        setdefaults(
            kwargs,
            dict(
                query__gui__class=Field.date,
                query__op_to_q_op=lambda op: {
                    '=': 'exact',
                    ':': 'contains'
                }.get(op) or Q_OP_BY_OP[op],
                bulk__class=Field.date,
            ))
        return Column(**kwargs)

    @staticmethod
    def datetime(**kwargs):
        setdefaults(
            kwargs,
            dict(
                query__gui__class=Field.date,
                query__op_to_q_op=lambda op: {
                    '=': 'exact',
                    ':': 'contains'
                }.get(op) or Q_OP_BY_OP[op],
                bulk__class=Field.date,
            ))
        return Column(**kwargs)

    @staticmethod
    def email(**kwargs):
        setdefaults(
            kwargs,
            dict(bulk__class=Field.email,
                 # TODO: query__class=Variable.email,
                 ))
        return Column(**kwargs)

    @staticmethod
    def from_model(model, field_name=None, model_field=None, **kwargs):
        return member_from_model(
            model=model,
            factory_lookup=_column_factory_by_field_type,
            factory_lookup_register_function=register_column_factory,
            field_name=field_name,
            model_field=model_field,
            defaults_factory=lambda model_field: {},
            **kwargs)

    @staticmethod
    def expand_member(model, field_name=None, model_field=None, **kwargs):
        return expand_member(model=model,
                             factory_lookup=_column_factory_by_field_type,
                             field_name=field_name,
                             model_field=model_field,
                             **kwargs)
コード例 #27
0
ファイル: __init__.py プロジェクト: TriOptima/tri.table
 def render_formatted(self):
     return evaluate(
         self.bound_column.cell.format, table=self.table, column=self.bound_column, row=self.row, value=self.value
     )
コード例 #28
0
ファイル: __init__.py プロジェクト: erik-sjoestedt/tri.table
 def render_formatted(self):
     return evaluate(self.bound_column.cell.format,
                     table=self.table,
                     column=self.bound_column,
                     row=self.row,
                     value=self.value)
コード例 #29
0
def test_evaluate_extra_kwargs_with_defaults():
    def f(x, y=17):
        return x

    assert 17 == evaluate(f, x=17)
コード例 #30
0
ファイル: __init__.py プロジェクト: pombredanne/tri.form
 def choices(form, field):
     return [None] + list(evaluate(original_choices, form=form, field=field))
コード例 #31
0
ファイル: __init__.py プロジェクト: pombredanne/tri.table
 def cell_contents(self, bound_row):
     return evaluate(self.cell__value, table=bound_row.table, column=self.column, row=bound_row.row)
コード例 #32
0
def test_evaluate_subset_parameters():
    def f(x, **_):
        return x

    assert 17 == evaluate(f, x=17, y=42)
コード例 #33
0
def test_evaluate_subset_parameters():
    def f(x, **_):
        return x

    assert 17 == evaluate(f, x=17, y=42)
コード例 #34
0
def test_no_evaluate_kwargs_mismatch():
    def f(x):
        return x * 2

    assert f is evaluate(f)
    assert f is evaluate(f, y=1)
コード例 #35
0
def create(request, model, title):
    return create_object(
        request=request,
        model=model,
        render__context__title=evaluate(title, model=model),
    )
コード例 #36
0
def test_no_evaluate_kwargs_mismatch():
    def f(x):
        return x * 2

    assert f is evaluate(f)
    assert f is evaluate(f, y=1)
コード例 #37
0
def test_evaluate_extra_kwargs_with_defaults():
    def f(x, y=17):
        return x

    assert 17 == evaluate(f, x=17)