Skip to content
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

Support quoting list values in mappings #443

Merged
merged 17 commits into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
6 changes: 6 additions & 0 deletions CHANGES/443.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
These changes fix https://github.com/aio-libs/aiohttp/issues/4714, that is,
webknjaz marked this conversation as resolved.
Show resolved Hide resolved
we now support the use of lists and tuples when quoting mappings such as
Python's builtin dict. As an example from the tests:

url = URL("http://example.com")
assert url.with_query({"a": [1, 2]}) == URL("http://example.com/?a=1&a=2")
10 changes: 10 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,9 @@ section generates a new *URL* instance.

The library accepts :class:`str` and :class:`int` as query argument values.

If a mapping such as :class:`dict` is used, the values may also be
:class:`list` or :class:`tuple` to represent a key has many values.

Please see :ref:`yarl-bools-support` for the reason why :class:`bool` is not
supported out-of-the-box.

Expand All @@ -556,6 +559,8 @@ section generates a new *URL* instance.
URL('http://example.com/path?c=d')
>>> URL('http://example.com/path?a=b').with_query({'c': 'd'})
URL('http://example.com/path?c=d')
>>> URL('http://example.com/path?a=b').with_query({'c': [1, 2]})
URL('http://example.com/path?c=1&c=2')
>>> URL('http://example.com/path?a=b').with_query({'кл': 'зн'})
URL('http://example.com/path?%D0%BA%D0%BB=%D0%B7%D0%BD')
>>> URL('http://example.com/path?a=b').with_query(None)
Expand Down Expand Up @@ -591,6 +596,9 @@ section generates a new *URL* instance.

The library accepts :class:`str` and :class:`int` as query argument values.

If a mapping such as :class:`dict` is used, the values may also be
:class:`list` or :class:`tuple` to represent a key has many values.

Please see :ref:`yarl-bools-support` for the reason why :class:`bool` is not
supported out-of-the-box.

Expand All @@ -600,6 +608,8 @@ section generates a new *URL* instance.
URL('http://example.com/path?a=b&c=d')
>>> URL('http://example.com/path?a=b').update_query({'c': 'd'})
URL('http://example.com/path?a=b&c=d')
>>> URL('http://example.com/path?a=b').update_query({'c': [1, 2]})
URL('http://example.com/path?a=b&c=1&c=2')
Lonami marked this conversation as resolved.
Show resolved Hide resolved
>>> URL('http://example.com/path?a=b').update_query({'кл': 'зн'})
URL('http://example.com/path?a=b&%D0%BA%D0%BB=%D0%B7%D0%BD')
>>> URL('http://example.com/path?a=b&b=1').update_query(b='2')
Expand Down
28 changes: 28 additions & 0 deletions tests/test_update_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,34 @@ def test_with_query_list_int():
assert str(url.with_query([("a", 1)])) == "http://example.com/?a=1"


@pytest.mark.parametrize(
"query,expected",
Lonami marked this conversation as resolved.
Show resolved Hide resolved
[
pytest.param({"a": [1, 2]}, "?a=1&a=2", id="list"),
pytest.param({"a": (1, 2)}, "?a=1&a=2", id="tuple"),
pytest.param({"a": ["1", 2]}, "?a=1&a=2", id="mixed types"),
pytest.param({"a": 1, "b": [2, 3]}, "?a=1&b=2&b=3", id="single then list",),
pytest.param({"a": [1, 2], "b": 3}, "?a=1&a=2&b=3", id="list then single",),
Lonami marked this conversation as resolved.
Show resolved Hide resolved
],
)
def test_with_query_sequence(query, expected):
url = URL("http://example.com")
assert url.with_query(query) == URL("http://example.com/" + expected)
Lonami marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.parametrize(
"query",
[
pytest.param({"a": [[1]]}, id="nested"),
pytest.param([("a", [1, 2])], id="tuple list"),
],
)
def test_with_query_sequence_invalid_use(query):
url = URL("http://example.com")
with pytest.raises(TypeError):
Lonami marked this conversation as resolved.
Show resolved Hide resolved
url.with_query(query)


def test_with_query_non_str():
url = URL("http://example.com")
with pytest.raises(TypeError):
Expand Down
17 changes: 14 additions & 3 deletions yarl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,15 @@ def with_path(self, path, *, encoded=False):
path = "/" + path
return URL(self._val._replace(path=path, query="", fragment=""), encoded=True)

@classmethod
def _query_seq_pairs(cls, quoter, pairs):
for key, val in pairs:
if isinstance(val, (list, tuple)):
for v in val:
yield quoter(key) + "=" + quoter(cls._query_var(v))
else:
yield quoter(key) + "=" + quoter(cls._query_var(val))

@staticmethod
def _query_var(v):
if isinstance(v, str):
Expand Down Expand Up @@ -882,9 +891,7 @@ def _get_str_query(self, *args, **kwargs):
query = ""
elif isinstance(query, Mapping):
quoter = self._QUERY_PART_QUOTER
query = "&".join(
quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query.items()
)
query = "&".join(self._query_seq_pairs(quoter, query.items()))
elif isinstance(query, str):
query = self._QUERY_QUOTER(query)
elif isinstance(query, (bytes, bytearray, memoryview)):
Expand All @@ -893,6 +900,10 @@ def _get_str_query(self, *args, **kwargs):
)
elif isinstance(query, Sequence):
quoter = self._QUERY_PART_QUOTER
# We don't expect sequence values if we're given a list of pairs
# already; only mappings like builtin `dict` which can't have the
# same key pointing to multiple values are allowed to use
# `_query_seq_pairs`.
query = "&".join(
quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query
)
Expand Down