Skip to content

Fix async sort filter #2082

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: stable
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/jinja2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:


@pass_environment
def do_sort(
def sync_do_sort(
environment: "Environment",
value: "t.Iterable[V]",
reverse: bool = False,
Expand Down Expand Up @@ -438,6 +438,20 @@ def do_sort(
return sorted(value, key=key_func, reverse=reverse)


@async_variant(sync_do_sort) # type: ignore
async def do_sort(
environment: "Environment",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
reverse: bool = False,
case_sensitive: bool = False,
attribute: t.Optional[t.Union[str, int]] = None,
) -> "t.List[V]":
key_func = make_multi_attrgetter(
environment, attribute, postprocess=ignore_case if not case_sensitive else None
)
return sorted(await auto_to_list(value), key=key_func, reverse=reverse)


@pass_environment
def sync_do_unique(
environment: "Environment",
Expand Down
6 changes: 6 additions & 0 deletions tests/test_async_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,12 @@ def test_simple_map(env_async, items):
assert tmpl.render(items=items) == "6"


@mark_dualiter("items", lambda: list("1423"))
def test_simple_map_sort(env_async, items):
tmpl = env_async.from_string('{{ items()|map("int")|sort }}')
assert tmpl.render(items=items) == "[1, 2, 3, 4]"


def test_map_sum(env_async): # async map + async filter
tmpl = env_async.from_string('{{ [[1,2], [3], [4,5,6]]|map("sum")|list }}')
assert tmpl.render() == "[3, 3, 15]"
Expand Down
Loading