action0-url 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ from .base import Url
2
+ from .params import Params
3
+
4
+ __version__: str = "0.1.0"
5
+
6
+ __all__ = ["Url", "Params"]
action0/url/base.py ADDED
@@ -0,0 +1,473 @@
1
+ import logging
2
+ from typing import Any
3
+ from urllib.parse import ParseResult
4
+ from urllib.parse import quote
5
+ from urllib.parse import unquote
6
+ from urllib.parse import urljoin
7
+ from urllib.parse import urlparse
8
+ from urllib.parse import urlunparse
9
+
10
+ from action0.url.params import Params
11
+ from action0.url.params import ParamTypes
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ # the default ports normalize() removes for the respective scheme
16
+ _DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21}
17
+
18
+ # characters that stay raw when percent-encoding a part (on top of quote()'s
19
+ # always-safe unreserved characters): RFC 3986 pchar minus the delimiters
20
+ # that would change how the URL is parsed back
21
+ _PATH_SAFE = "/:@!$&'()*+,=" # no ";", it starts the path params
22
+ _FRAGMENT_SAFE = "/?:@!$&'()*+,;="
23
+ _USERINFO_SAFE = "!$&'()*+,;=" # no ":", it separates username and password
24
+
25
+
26
+ def _split_authority(authority: str) -> tuple[str | None, int | None]:
27
+ """
28
+ Split an authority ("hostname" or "hostname:port") into its parts.
29
+
30
+ :param authority: the authority string to split
31
+ :return: a tuple of the hostname and the port
32
+ """
33
+ # split on the last ":" and only if digits follow it, so IPv6 literals
34
+ # like "[::1]" (colons but no port) stay intact
35
+ host_part, sep, port_part = authority.rpartition(":")
36
+ if sep and port_part.isdigit():
37
+ return host_part, int(port_part)
38
+ return authority or None, None
39
+
40
+
41
+ def _encode_hostname(hostname: str) -> str:
42
+ """
43
+ IDNA-encode (punycode) a hostname if it contains non-ASCII characters.
44
+
45
+ :param hostname: the hostname to encode
46
+ :return: the ASCII representation of the hostname
47
+ :raises UnicodeError: if the hostname cannot be IDNA-encoded
48
+ """
49
+ if hostname.isascii():
50
+ return hostname
51
+ return hostname.encode("idna").decode("ascii")
52
+
53
+
54
+ def _resolve_dot_segments(path: str) -> str:
55
+ """
56
+ Remove "." and ".." segments from a path as described in
57
+ RFC 3986, section 5.2.4.
58
+
59
+ :param path: the path to resolve
60
+ :return: the path without any "." or ".." segments
61
+ """
62
+ input_ = path
63
+ output: list[str] = []
64
+ while input_:
65
+ if input_.startswith("../"):
66
+ input_ = input_[3:]
67
+ elif input_.startswith("./"):
68
+ input_ = input_[2:]
69
+ elif input_.startswith("/./"):
70
+ input_ = "/" + input_[3:]
71
+ elif input_ == "/.":
72
+ input_ = "/"
73
+ elif input_.startswith("/../"):
74
+ input_ = "/" + input_[4:]
75
+ if output:
76
+ output.pop()
77
+ elif input_ == "/..":
78
+ input_ = "/"
79
+ if output:
80
+ output.pop()
81
+ elif input_ in (".", ".."):
82
+ input_ = ""
83
+ else:
84
+ # move the first segment (incl. its leading "/") to the output
85
+ start = 1 if input_.startswith("/") else 0
86
+ next_slash = input_.find("/", start)
87
+ if next_slash == -1:
88
+ output.append(input_)
89
+ input_ = ""
90
+ else:
91
+ output.append(input_[:next_slash])
92
+ input_ = input_[next_slash:]
93
+ return "".join(output)
94
+
95
+
96
+ class Url:
97
+ """
98
+ Python presentation of a parsed URL to allow easy manipulation of its
99
+ parts.
100
+
101
+ Example::
102
+
103
+ >>> url = Url("https://www.example.com/path/filename.json?foo=bar")
104
+ >>> url.query.set("foo", "baz")
105
+ >>> url.as_str()
106
+ 'https://www.example.com/path/filename.json?foo=baz'
107
+ >>> url.query.add("a", "b")
108
+ >>> url.as_str()
109
+ 'https://www.example.com/path/filename.json?foo=baz&a=b'
110
+ >>> # allow params with multiple values (added at the end)
111
+ >>> url.query.add("foo", "123")
112
+ >>> url.as_str()
113
+ 'https://www.example.com/path/filename.json?foo=baz&a=b&foo=123'
114
+ >>> url.hostname = "action0.com"
115
+ >>> url.port = 8443
116
+ >>> url.path = "/public/index.html"
117
+ >>> url.username = "user"
118
+ >>> url.password = "pass"
119
+ >>> url.fragment = "fragment"
120
+ >>> url.as_str()
121
+ 'https://user:pass@action0.com:8443/public/index.html?foo=baz&a=b&foo=123#fragment'
122
+
123
+ Based on the named tuple that :py:meth:`urllib.parse.urlparse` returns.
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ url: str | None = None,
129
+ *,
130
+ scheme: str | None = None,
131
+ hostname: str | None = None,
132
+ path: str | None = None,
133
+ query: ParamTypes | None = None,
134
+ path_params: ParamTypes | None = None,
135
+ fragment: str | None = None,
136
+ username: str | None = None,
137
+ password: str | None = None,
138
+ port: int | None = None,
139
+ authority: str | None = None,
140
+ ) -> None:
141
+ """
142
+ If a `url` is given it will use this as base and other
143
+ parameters will replace/overwrite the parts of the url string.
144
+
145
+ The parts of a parsed `url` are stored percent-decoded, i.e. the
146
+ attributes hold the readable values ("my file.html", not
147
+ "my%20file.html") and :py:meth:`as_str` encodes them again; values
148
+ given as keyword arguments are expected to be unencoded as well.
149
+ Be aware that an encoded "/" (%2F) inside a path segment is decoded
150
+ like everything else and hence becomes a segment separator when the
151
+ URL is rendered again.
152
+
153
+ Example::
154
+
155
+ >>> url = Url("https://www.example.com/path/filename.json")
156
+ >>> url.as_str()
157
+ 'https://www.example.com/path/filename.json'
158
+ >>> url = Url("https://www.example.com/path/filename.json", path="/hello/world.html")
159
+ >>> url.as_str()
160
+ 'https://www.example.com/hello/world.html'
161
+ >>> url = Url("https://www.example.com?foo=bar", query={"bar": "baz"})
162
+ >>> url.as_str()
163
+ 'https://www.example.com?bar=baz'
164
+
165
+
166
+ :param url: the optional string representation of a URL to use as base
167
+ :param scheme: the url scheme, e.g. https, ftps, etc.
168
+ :param hostname: the hostname (domain incl. subdomain, or IP-Address, etc.)
169
+ :param path: the path to the file (including the file's name)
170
+ :param query: the query parameters
171
+ :param path_params: the file parameters, k=v pairs after the path separated with a ';'
172
+ (not commonly used, maybe you saw something like
173
+ 'https://example.com/path/file.html;jsessionid=1234')
174
+ :param fragment: everything after the '#' usually only interpreted by the client
175
+ :param username: if the username / password is part of the URL, e.g.
176
+ 'https://user:pass@example.com/'
177
+ :param password: if the username / password is part of the URL, e.g.
178
+ 'https://user:pass@example.com/'
179
+ :param port: the port to connect to
180
+ :param authority: also known as netloc, a combination of hostname and port and
181
+ hence can't be combined with hostname or port.
182
+ :raises ValueError: if authority is combined with hostname or port
183
+ """
184
+ if authority:
185
+ if hostname or port:
186
+ raise ValueError("Cannot specify both authority and hostname or port")
187
+ hostname, port = _split_authority(authority)
188
+
189
+ if url is not None:
190
+ parse_result = urlparse(url, scheme="https")
191
+ else:
192
+ # an all-empty parse result so the lookups below fall through to
193
+ # the keyword arguments (and "" for the unset string parts)
194
+ parse_result = ParseResult(
195
+ scheme="", netloc="", path="", params="", query="", fragment=""
196
+ )
197
+
198
+ self.scheme = scheme or parse_result.scheme
199
+ self.hostname = hostname or parse_result.hostname
200
+ self.port = port or parse_result.port
201
+ # parsed parts are percent-decoded here and re-encoded in as_str();
202
+ # the attributes always hold the readable values
203
+ self.path = path or unquote(parse_result.path)
204
+ self.fragment = fragment or unquote(parse_result.fragment)
205
+ parsed_username = parse_result.username
206
+ self.username = username or (unquote(parsed_username) if parsed_username else None)
207
+ parsed_password = parse_result.password
208
+ self.password = password or (unquote(parsed_password) if parsed_password else None)
209
+ self.query = Params(query or parse_result.query or "")
210
+ # path params use ";" to separate the k=v pairs from the path and each other
211
+ self.path_params = Params(path_params or parse_result.params or "", separator=";")
212
+
213
+ @property
214
+ def authority(self) -> str:
215
+ """
216
+ The "hostname:port" combination (also known as netloc), just the
217
+ hostname if no port is set. Assigning a string of the same form
218
+ replaces hostname and port.
219
+ """
220
+ host = self.hostname or ""
221
+ if self.port:
222
+ return f"{host}:{self.port}"
223
+ return host
224
+
225
+ @authority.setter
226
+ def authority(self, value: str) -> None:
227
+ self.hostname, self.port = _split_authority(value)
228
+
229
+ @property
230
+ def parent(self) -> "Url":
231
+ """
232
+ A copy of this URL with the last path segment removed; the other
233
+ parts are kept. Like in pathlib, the parent of the root is the root.
234
+ """
235
+ parent_path, sep, _ = self.path.rstrip("/").rpartition("/")
236
+ if sep:
237
+ new_path = parent_path or "/"
238
+ else:
239
+ # no slash left: the parent of a bare relative segment is empty,
240
+ # the parent of the root stays the root
241
+ new_path = "/" if self.path.startswith("/") else ""
242
+ return self.copy(path=new_path)
243
+
244
+ @property
245
+ def name(self) -> str:
246
+ """
247
+ The last path segment (usually the file name); "" if the path is
248
+ empty or ends with a "/". Assigning replaces the last segment.
249
+ """
250
+ return self.path.rpartition("/")[2]
251
+
252
+ @name.setter
253
+ def name(self, value: str) -> None:
254
+ base, sep, _ = self.path.rpartition("/")
255
+ self.path = f"{base}{sep}{value}"
256
+
257
+ @property
258
+ def suffix(self) -> str:
259
+ """
260
+ The file extension of :py:attr:`name` including the ".";
261
+ "" if there is none.
262
+ """
263
+ name = self.name
264
+ dot_index = name.rfind(".")
265
+ # a name that is only a dotfile (".hidden") has no suffix
266
+ return name[dot_index:] if dot_index > 0 else ""
267
+
268
+ def as_str(self) -> str:
269
+ """
270
+ Assemble the (possibly modified) parts back into a URL string.
271
+ The parts are percent-encoded as needed and a non-ASCII hostname
272
+ is IDNA-encoded (punycode).
273
+
274
+ :return: the string representation of the URL
275
+ :raises UnicodeError: if the hostname cannot be IDNA-encoded
276
+ """
277
+ # the authority optionally has the port, username and password
278
+ authority = _encode_hostname(self.hostname) if self.hostname else ""
279
+ if self.port:
280
+ authority = f"{authority}:{self.port}"
281
+
282
+ if self.username:
283
+ userinfo = quote(self.username, safe=_USERINFO_SAFE)
284
+ if self.password:
285
+ userinfo = f"{userinfo}:{quote(self.password, safe=_USERINFO_SAFE)}"
286
+ authority = f"{userinfo}@{authority}"
287
+ elif self.password:
288
+ log.warning("password given but no username, password is discarded!")
289
+
290
+ # urlunparse seems to be badly supported by the type-checker
291
+ parts = (
292
+ self.scheme,
293
+ authority,
294
+ quote(self.path, safe=_PATH_SAFE),
295
+ self.path_params.as_str(),
296
+ self.query.as_str(),
297
+ quote(self.fragment, safe=_FRAGMENT_SAFE),
298
+ )
299
+ return str(urlunparse(parts))
300
+
301
+ def join(self, other: "str | Url") -> "Url":
302
+ """
303
+ Resolve another, possibly relative, URL against this one — like a
304
+ browser resolves a link on a page — wrapping
305
+ :py:func:`urllib.parse.urljoin`.
306
+
307
+ Example::
308
+
309
+ >>> Url("https://example.com/a/b").join("c")
310
+ Url(https://example.com/a/c)
311
+ >>> Url("https://example.com/a/b").join("/x")
312
+ Url(https://example.com/x)
313
+
314
+ :param other: the URL to resolve against this one
315
+ :return: a new Url, this instance is not modified
316
+ """
317
+ return Url(urljoin(self.as_str(), str(other)))
318
+
319
+ def __truediv__(self, segment: str) -> "Url":
320
+ """
321
+ Return a copy with the segment(s) appended to the path, always
322
+ joined with exactly one "/".
323
+
324
+ Example::
325
+
326
+ >>> Url("https://example.com") / "api" / "v2"
327
+ Url(https://example.com/api/v2)
328
+
329
+ :param segment: the path segment(s) to append
330
+ :return: a new Url, this instance is not modified
331
+ """
332
+ copied = self.copy()
333
+ copied.path = f"{self.path.rstrip('/')}/{segment.lstrip('/')}"
334
+ return copied
335
+
336
+ def copy(self, **overrides: Any) -> "Url":
337
+ """
338
+ An independent copy of this URL, optionally with parts replaced.
339
+
340
+ Example::
341
+
342
+ >>> url = Url("https://example.com:8443/index.html")
343
+ >>> url.copy(scheme="http", port=None)
344
+ Url(http://example.com/index.html)
345
+
346
+ :param overrides: any URL part accepted by the constructor
347
+ :return: a new Url, this instance is not modified
348
+ :raises TypeError: on part names the constructor does not know
349
+ :raises ValueError: if authority is combined with hostname or port
350
+ """
351
+ parts: dict[str, Any] = {
352
+ "scheme": self.scheme,
353
+ "hostname": self.hostname,
354
+ "port": self.port,
355
+ "path": self.path,
356
+ "query": self.query,
357
+ "path_params": self.path_params,
358
+ "fragment": self.fragment,
359
+ "username": self.username,
360
+ "password": self.password,
361
+ }
362
+ if "authority" in overrides:
363
+ # the constructor rejects authority combined with hostname / port
364
+ del parts["hostname"]
365
+ del parts["port"]
366
+ parts.update(overrides)
367
+ return Url(**parts)
368
+
369
+ def origin(self) -> "Url":
370
+ """
371
+ The origin — scheme, hostname and port only — e.g. for same-origin
372
+ comparisons or as a base to build new URLs on.
373
+
374
+ :return: a new Url with only scheme, hostname and port set
375
+ """
376
+ return Url(scheme=self.scheme, hostname=self.hostname, port=self.port)
377
+
378
+ def normalize(self) -> "Url":
379
+ """
380
+ A normalized copy of this URL (RFC 3986 style): scheme and hostname
381
+ lowercased, the scheme's default port removed, "." and ".." path
382
+ segments resolved, and an empty path becomes "/" if there is a
383
+ hostname.
384
+
385
+ Example::
386
+
387
+ >>> Url("https://example.com:443/a/./b/../c").normalize()
388
+ Url(https://example.com/a/c)
389
+
390
+ :return: a new Url, this instance is not modified
391
+ """
392
+ scheme = self.scheme.lower()
393
+ hostname = self.hostname.lower() if self.hostname else self.hostname
394
+ port = self.port
395
+ if port is not None and _DEFAULT_PORTS.get(scheme) == port:
396
+ port = None
397
+ path = _resolve_dot_segments(self.path)
398
+ if hostname and not path:
399
+ path = "/"
400
+ return self.copy(scheme=scheme, hostname=hostname, port=port, path=path)
401
+
402
+ def as_dict(self) -> dict[str, Any]:
403
+ """
404
+ The URL parts as a plain dictionary (query and path params as
405
+ dictionaries of value lists), e.g. for debugging or serialization.
406
+ Contains the real password — use repr() for a redacted view.
407
+
408
+ :return: a dictionary of all URL parts
409
+ """
410
+ return {
411
+ "scheme": self.scheme,
412
+ "username": self.username,
413
+ "password": self.password,
414
+ "hostname": self.hostname,
415
+ "port": self.port,
416
+ "path": self.path,
417
+ "path_params": self.path_params.as_dict(),
418
+ "query": self.query.as_dict(),
419
+ "fragment": self.fragment,
420
+ }
421
+
422
+ def as_parse_result(self) -> ParseResult:
423
+ """
424
+ The URL as the named tuple :py:func:`urllib.parse.urlparse` returns,
425
+ for interoperability with stdlib-based code. The parts are
426
+ percent-encoded like in :py:meth:`as_str`.
427
+
428
+ :return: the ParseResult of the assembled URL string
429
+ """
430
+ return urlparse(self.as_str())
431
+
432
+ def is_absolute(self) -> bool:
433
+ """
434
+ :return: whether the URL has a hostname
435
+ """
436
+ return self.hostname is not None
437
+
438
+ def is_relative(self) -> bool:
439
+ """
440
+ :return: whether the URL has no hostname
441
+ """
442
+ return not self.is_absolute()
443
+
444
+ def __eq__(self, other: object) -> bool:
445
+ """
446
+ Two Urls are equal if all their parts are equal. The order of query
447
+ parameter names doesn't matter (``?a=1&b=2`` equals ``?b=2&a=1``),
448
+ the order of multiple values of the same name does.
449
+
450
+ :param other: the Url to compare with
451
+ :return: whether the URLs are equal
452
+ """
453
+ if not isinstance(other, Url):
454
+ return NotImplemented
455
+ return (
456
+ self.scheme == other.scheme
457
+ and self.hostname == other.hostname
458
+ and self.port == other.port
459
+ and self.path == other.path
460
+ and self.path_params == other.path_params
461
+ and self.query == other.query
462
+ and self.fragment == other.fragment
463
+ and self.username == other.username
464
+ and self.password == other.password
465
+ )
466
+
467
+ def __str__(self) -> str:
468
+ return self.as_str()
469
+
470
+ def __repr__(self) -> str:
471
+ # don't leak credentials into logs and tracebacks
472
+ url = self.copy(password="***") if self.password else self
473
+ return f"{self.__class__.__name__}({url.as_str()})"
action0/url/params.py ADDED
@@ -0,0 +1,394 @@
1
+ from typing import Iterable
2
+ from typing import Iterator
3
+ from typing import Literal
4
+ from typing import Mapping
5
+ from typing import MutableMapping
6
+ from typing import Union
7
+ from typing import cast
8
+ from urllib.parse import parse_qsl
9
+ from urllib.parse import urlencode
10
+
11
+ ParamValue = Union[str, int, float, bool]
12
+ """A single parameter value; non-strings are coerced to strings on the way in
13
+ (bools become the web-style ``"true"`` / ``"false"``)."""
14
+
15
+ # Mapping instead of dict so callers may pass any dict-ish type and, unlike
16
+ # dict, Mapping is covariant in its value type (a dict[str, str] works too)
17
+ ParamTypes = Union[
18
+ Iterable[tuple[str, Union[ParamValue, Iterable[ParamValue]]]],
19
+ Mapping[str, Union[ParamValue, Iterable[ParamValue]]],
20
+ str,
21
+ ]
22
+ """Everything that can initialize a :py:class:`Params` instance: a query
23
+ string, a mapping, or an iterable of name/value(s) tuples."""
24
+
25
+
26
+ def _coerce_value(value: ParamValue) -> str:
27
+ """
28
+ Coerce a single parameter value to its string representation.
29
+
30
+ :param value: the value to coerce
31
+ :return: the value as a string, bools as "true" / "false"
32
+ """
33
+ # bool before the plain str() fallback: bools use the web convention
34
+ if isinstance(value, bool):
35
+ return "true" if value else "false"
36
+ if isinstance(value, str):
37
+ return value
38
+ return str(value)
39
+
40
+
41
+ def _coerce_values(value_s: Union[ParamValue, Iterable[ParamValue]]) -> list[str]:
42
+ """
43
+ Coerce a single value or an iterable of values to a list of strings.
44
+
45
+ :param value_s: a single value or an iterable of values
46
+ :return: all values as a list of strings
47
+ """
48
+ if isinstance(value_s, (str, int, float, bool)):
49
+ return [_coerce_value(value_s)]
50
+ return [_coerce_value(value_) for value_ in value_s]
51
+
52
+
53
+ class Params(MutableMapping[str, str]):
54
+ """
55
+ Allows easy manipulation of URL query parameters and URL path parameters, it
56
+ supports single and multiple values for a key.
57
+
58
+ Internally the parameters are an ordered list of ``(key, value)`` pairs, so
59
+ the full representation order — including values of one key interleaved
60
+ with other keys — round-trips losslessly:
61
+ ``Params("a=1&b=2&a=3").as_str()`` is ``"a=1&b=2&a=3"`` again. The grouped
62
+ views (:py:meth:`as_dict`, :py:meth:`as_tuples`) collect the values per
63
+ key instead.
64
+
65
+ Params implements :py:class:`typing.MutableMapping`: the mapping view
66
+ (``params[key]``, :py:meth:`get`, ``items()``, ``values()``, ...) works
67
+ with a single value per key — the last one, like :py:meth:`singles`.
68
+ Multi-value access is available through :py:meth:`get_all`,
69
+ :py:meth:`add`, :py:meth:`as_dict` and :py:meth:`as_tuples`.
70
+
71
+ Example::
72
+
73
+ >>> params = Params("b=2&a=1")
74
+ >>> params["a"]
75
+ '1'
76
+ >>> params.add("a", 3)
77
+ >>> params.get_all("a")
78
+ ['1', '3']
79
+ >>> params.as_str()
80
+ 'b=2&a=1&a=3'
81
+ >>> params.as_str(sort=True)
82
+ 'a=1&a=3&b=2'
83
+ """
84
+
85
+ def __init__(
86
+ self, params: Union[ParamTypes, None] = None, separator: Literal["&", ";"] = "&"
87
+ ) -> None:
88
+ """
89
+ :param params: the initial key-value(s) to set, either as a string which
90
+ will be parsed using parse_qsl, another Params instance
91
+ whose pairs are copied, or as a list of tuples or a
92
+ dictionary. The values can be single values or lists
93
+ of values; non-string values are coerced to strings
94
+ (bools become "true" / "false"). Unlike parse_qsl's
95
+ default, blank values are kept ("a=&b=1" keeps "a"), so
96
+ parsing and re-rendering is lossless.
97
+ :param separator: either a '&' or a ';' to separate the key-value pairs
98
+ in the string representation (also used when copying
99
+ another Params instance)
100
+ """
101
+ self._pairs: list[tuple[str, str]] = []
102
+ self.separator: Literal["&", ";"] = separator
103
+
104
+ if isinstance(params, Params):
105
+ self._pairs = list(params._pairs)
106
+
107
+ elif isinstance(params, str):
108
+ self._pairs = parse_qsl(params, separator=self.separator, keep_blank_values=True)
109
+
110
+ elif isinstance(params, Mapping):
111
+ # cast: the type checker cannot fully rule out the Iterable-of-tuples
112
+ # union member here because a Mapping is itself an Iterable
113
+ mapping = cast("Mapping[str, Union[ParamValue, Iterable[ParamValue]]]", params)
114
+ for key, value_s in mapping.items():
115
+ self.add(key, value_s)
116
+
117
+ elif isinstance(params, Iterable):
118
+ for key, value_s in params:
119
+ self.add(key, value_s)
120
+
121
+ def __getitem__(self, key: str) -> str:
122
+ """
123
+ The single value of the parameter; if the parameter has multiple
124
+ values, the last one — like :py:meth:`singles`. Use
125
+ :py:meth:`get_all` for all values.
126
+
127
+ :param key: the parameter name
128
+ :return: the (last) value of the parameter
129
+ :raises KeyError: if the parameter does not exist
130
+ """
131
+ for pair_key, value in reversed(self._pairs):
132
+ if pair_key == key:
133
+ return value
134
+ raise KeyError(key)
135
+
136
+ def __setitem__(self, key: str, value: Union[ParamValue, Iterable[ParamValue]]) -> None:
137
+ """
138
+ Replace all values of the parameter, same as :py:meth:`set`.
139
+
140
+ :param key: the parameter name
141
+ :param value: a single value or a list of values
142
+ """
143
+ self.set(key, value)
144
+
145
+ def __delitem__(self, key: str) -> None:
146
+ """
147
+ Remove the parameter with all its values.
148
+
149
+ :param key: the parameter name
150
+ :raises KeyError: if the parameter does not exist
151
+ """
152
+ if not self.remove(key):
153
+ raise KeyError(key)
154
+
155
+ def __iter__(self) -> Iterator[str]:
156
+ """
157
+ :return: an iterator over the distinct parameter names in the order
158
+ of their first pair
159
+ """
160
+ seen: set[str] = set()
161
+ for key, _ in self._pairs:
162
+ if key not in seen:
163
+ seen.add(key)
164
+ yield key
165
+
166
+ def __len__(self) -> int:
167
+ """
168
+ :return: the number of distinct parameter names
169
+ """
170
+ return len({key for key, _ in self._pairs})
171
+
172
+ def __contains__(self, key: object) -> bool:
173
+ """
174
+ :param key: the parameter name
175
+ :return: whether a parameter with this name exists
176
+ """
177
+ return any(pair_key == key for pair_key, _ in self._pairs)
178
+
179
+ def get_all(self, key: str) -> list[str]:
180
+ """
181
+ All values of the parameter in representation order; use
182
+ ``params[key]`` or :py:meth:`get` for the single-value view.
183
+
184
+ :param key: the parameter name
185
+ :return: the values as a list, an empty list if the parameter
186
+ does not exist
187
+ """
188
+ return [value for pair_key, value in self._pairs if pair_key == key]
189
+
190
+ def add(self, key: str, value: Union[ParamValue, Iterable[ParamValue]]) -> None:
191
+ """
192
+ Add a parameter with a single value or multiple values, appended at
193
+ the end of the representation. If it is a single value, the query
194
+ string equivalent would be something like "foo=bar". If it is a
195
+ list of values, the query string equivalent would be something like
196
+ "foo=bar&foo=baz&foo=abc". Existing values are kept (in place).
197
+
198
+ :param key: the parameter name to add
199
+ :param value: the parameter value or list of values to add
200
+ """
201
+ self._pairs.extend((key, value_) for value_ in _coerce_values(value))
202
+
203
+ def remove(
204
+ self, key: str, value: Union[ParamValue, Iterable[ParamValue], None] = None
205
+ ) -> list[str]:
206
+ """
207
+ If only a key is given all values with this name are removed. If a
208
+ value or a list of values is given only the matching values are removed.
209
+
210
+ :param key: the name of the parameter to remove (or from which values
211
+ are to be removed)
212
+ :param value: if given, only matching value(s) are to be removed not the
213
+ entire parameter
214
+ :return: a list of removed values
215
+ """
216
+ value_list = None if value is None else _coerce_values(value)
217
+
218
+ kept: list[tuple[str, str]] = []
219
+ removed: list[str] = []
220
+ for pair_key, pair_value in self._pairs:
221
+ if pair_key == key and (value_list is None or pair_value in value_list):
222
+ removed.append(pair_value)
223
+ else:
224
+ kept.append((pair_key, pair_value))
225
+
226
+ self._pairs = kept
227
+ return removed
228
+
229
+ def set(self, key: str, value: Union[ParamValue, Iterable[ParamValue]]) -> None:
230
+ """
231
+ Replace all value(s) of the key with the value(s) given, at the
232
+ position of the key's first pair (new keys are appended at the
233
+ end). Setting an empty list of values removes the key.
234
+
235
+ :param key: the key to set values for
236
+ :param value: a single value or a list of values to set
237
+ """
238
+ values = _coerce_values(value)
239
+ if not values:
240
+ self.remove(key)
241
+ return
242
+
243
+ new_pairs: list[tuple[str, str]] = []
244
+ inserted = False
245
+ for pair_key, pair_value in self._pairs:
246
+ if pair_key == key:
247
+ # replace the key's first pair with the new values, drop the
248
+ # other pairs of the key
249
+ if not inserted:
250
+ new_pairs.extend((key, value_) for value_ in values)
251
+ inserted = True
252
+ else:
253
+ new_pairs.append((pair_key, pair_value))
254
+ if not inserted:
255
+ new_pairs.extend((key, value_) for value_ in values)
256
+ self._pairs = new_pairs
257
+
258
+ # narrower than the MutableMapping contract on purpose: update() accepts
259
+ # the same input forms as the constructor (e.g. a query string) instead of
260
+ # arbitrary keys()/__getitem__ objects
261
+ def update( # type: ignore[override] # ty: ignore[invalid-method-override]
262
+ self,
263
+ params: Union[ParamTypes, None] = None,
264
+ **kwargs: Union[ParamValue, Iterable[ParamValue]],
265
+ ) -> None:
266
+ """
267
+ Merge the given parameters into this instance: values of keys that
268
+ already exist are replaced (like ``dict.update``, at the position of
269
+ the key's first pair), other keys are appended. Accepts the same
270
+ forms as the constructor (query string, mapping, iterable of tuples,
271
+ Params instance) plus keyword arguments.
272
+
273
+ :param params: the parameters to merge in
274
+ :param kwargs: parameters to merge in given as keyword arguments
275
+ """
276
+ if params is not None:
277
+ other = Params(params, self.separator)
278
+ for key in other:
279
+ self.set(key, other.get_all(key))
280
+ for key, value_s in kwargs.items():
281
+ self.set(key, value_s)
282
+
283
+ def clear(self) -> dict[str, list[str]]: # type: ignore[override] # ty: ignore[invalid-method-override]
284
+ """
285
+ Remove all parameters, returns a dictionary of the
286
+ cleared parameters (unlike ``MutableMapping.clear`` which
287
+ returns ``None``).
288
+
289
+ :return: a dictionary of removed keys and values
290
+ """
291
+ old = self.as_dict()
292
+ self._pairs = []
293
+ return old
294
+
295
+ def sort(self) -> None:
296
+ """
297
+ Sort the pairs in place by their name and then by their values — the
298
+ persistent equivalent of ``as_str(sort=True)``, which only sorts the
299
+ rendered output.
300
+ """
301
+ self._pairs.sort()
302
+
303
+ def as_str(self, sort: bool = False) -> str:
304
+ """
305
+ A string representation of the parameters, url encoded.
306
+
307
+ :param sort: sort the parameters by their name and then by their value, otherwise
308
+ they'll be returned in the order of the representation
309
+ :return: the url encoded query / file parameter string, e.g.
310
+ "foo=bar&bar=baz&bar=abc"
311
+ """
312
+ pairs = sorted(self._pairs) if sort else self._pairs
313
+
314
+ param_str = urlencode(pairs)
315
+
316
+ # urlencode always joins with "&"; a literal separator inside a value is
317
+ # percent-encoded by then, so a plain replace cannot corrupt values
318
+ if self.separator != "&":
319
+ param_str = param_str.replace("&", self.separator)
320
+
321
+ return param_str
322
+
323
+ def as_tuples(self) -> Iterator[tuple[str, list[str]]]:
324
+ """
325
+ :return: the parameters grouped per key as an iterator of tuples with
326
+ the values being lists of strings
327
+ """
328
+ return iter(self.as_dict().items())
329
+
330
+ def as_single_tuples(self) -> Iterator[tuple[str, str]]:
331
+ """
332
+ :return: the parameter representation as an iterator of tuples of
333
+ the key and a single value, in representation order. This
334
+ means keys with multiple values will appear more than once.
335
+ """
336
+ return iter(list(self._pairs))
337
+
338
+ def as_dict(self) -> dict[str, list[str]]:
339
+ """
340
+ :return: the parameters grouped per key as a dictionary with the
341
+ parameter names as key and the values as lists of strings
342
+ """
343
+ result: dict[str, list[str]] = {}
344
+ for key, value in self._pairs:
345
+ result.setdefault(key, []).append(value)
346
+ return result
347
+
348
+ def singles(self) -> dict[str, str]:
349
+ """
350
+ For those who are really sure that each parameter has only one value
351
+ and do not want to bother with the lists for the values, this method
352
+ will return only the last value for each key.
353
+
354
+ WARNING: be aware, if the key has multiple values, only one of those
355
+ will be returned for the key!
356
+
357
+ :return: a dictionary with the parameters with a single value
358
+ for each key
359
+ """
360
+ return {key: values[-1] for key, values in self.as_dict().items()}
361
+
362
+ def uniq_tuples(self) -> Iterator[tuple[str, str]]:
363
+ """
364
+ Same as :py:meth:`singles` but returning tuples.
365
+
366
+ WARNING: be aware, if the key has multiple values, only one of those
367
+ will be returned for the key!
368
+
369
+ :return: an iterable of tuples with a key and a single value
370
+ """
371
+ return iter(self.singles().items())
372
+
373
+ def __eq__(self, other: object) -> bool:
374
+ """
375
+ Params are equal when they hold the same keys with the same values in
376
+ the same per-key order; the order of the keys and the separator don't
377
+ matter. Plain mappings are converted to Params before comparing.
378
+
379
+ :param other: the Params instance or mapping to compare with
380
+ :return: whether the parameters are equal
381
+ """
382
+ if isinstance(other, Params):
383
+ return self.as_dict() == other.as_dict()
384
+ if isinstance(other, Mapping):
385
+ # cast: the values of an arbitrary mapping are unknown to the
386
+ # type checker; non-string values are coerced like everywhere else
387
+ return self.as_dict() == Params(cast("ParamTypes", other)).as_dict()
388
+ return NotImplemented
389
+
390
+ def __str__(self) -> str:
391
+ return self.as_str()
392
+
393
+ def __repr__(self) -> str:
394
+ return f"{self.__class__.__name__}({self.as_str()})"
action0/url/py.typed ADDED
File without changes
@@ -0,0 +1,245 @@
1
+ Metadata-Version: 2.4
2
+ Name: action0-url
3
+ Version: 0.1.0
4
+ Summary: Library for easily parsing and manipulating URLs
5
+ Project-URL: Homepage, https://github.com/LaughInJar/action0-url
6
+ Project-URL: Documentation, https://laughinjar.github.io/action0-url/
7
+ Project-URL: Source, https://github.com/LaughInJar/action0-url
8
+ Project-URL: Issues, https://github.com/LaughInJar/action0-url/issues
9
+ Author: Simon Lachinger
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: manipulation,parse,query,url,urllib
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Topic :: Internet :: WWW/HTTP
23
+ Classifier: Topic :: Software Development :: Libraries
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.11
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Action0-Url
29
+
30
+ [![CI](https://github.com/LaughInJar/action0-url/actions/workflows/ci.yml/badge.svg)](https://github.com/LaughInJar/action0-url/actions/workflows/ci.yml)
31
+ [![PyPI](https://img.shields.io/pypi/v/action0-url)](https://pypi.org/project/action0-url/)
32
+
33
+ Easy URL parsing, manipulation and unparsing wrapper around
34
+ urllib.parse's methods.
35
+
36
+ Requires Python 3.11 or newer.
37
+
38
+ Full documentation including the API reference:
39
+ <https://laughinjar.github.io/action0-url/>
40
+
41
+ ## Installation
42
+
43
+ ```shell
44
+ pip install action0-url # or: uv add action0-url
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ Either with an existing url:
50
+
51
+ ```python
52
+ from action0.url import Url
53
+
54
+ url = Url("https://www.example.com/path/filename.json?foo=bar")
55
+ url.query.set("foo", "baz")
56
+ print(url.as_str())
57
+ # https://www.example.com/path/filename.json?foo=baz
58
+ url.query.add("a", "b")
59
+ print(url.as_str())
60
+ # https://www.example.com/path/filename.json?foo=baz&a=b
61
+ url.query.add("foo", "123")
62
+ print(url.as_str())
63
+ # https://www.example.com/path/filename.json?foo=baz&a=b&foo=123
64
+ url.hostname = "action0.com"
65
+ url.port = 8443
66
+ url.path = "/public/index.html"
67
+ url.username = "user"
68
+ url.password = "pass"
69
+ url.fragment = "fragment"
70
+ # instead of url.as_str() you can also use str(url) or just print(url)
71
+ print(url)
72
+ ```
73
+
74
+ Or construct one (and manipulate):
75
+
76
+ ```python
77
+ from action0.url import Url
78
+
79
+ url = Url(
80
+ scheme="https",
81
+ hostname="example.com",
82
+ path="index.html",
83
+ query={"a": "b", "foo": ["bar", "baz"]},
84
+ port=1234
85
+ )
86
+ print(url)
87
+ # https://example.com:1234/index.html?a=b&foo=bar&foo=baz
88
+ url.username="myuser"
89
+ url.port=None
90
+ print(url)
91
+ # 'https://myuser@example.com/index.html?a=b&foo=bar&foo=baz'
92
+ ```
93
+
94
+ ## Working with query parameters
95
+
96
+ `url.query` is a `Params` instance which supports single and multiple
97
+ values per parameter name. It behaves like a dict (a `MutableMapping`)
98
+ where subscription works with a single value per name — the last one —
99
+ while `add()`, `get_all()` and friends handle multiple values:
100
+
101
+ ```python
102
+ from action0.url import Url
103
+
104
+ url = Url("https://example.com/?b=2&a=1&a=3")
105
+ url.query["c"] = "4" # replace/set values, like Params.set()
106
+ url.query.add("c", ["x", 5]) # non-strings are coerced, bools become "true"/"false"
107
+ url.query.remove("a", "1")
108
+ print(url.query["a"]) # the single (last) value; use get() for a default
109
+ # 3
110
+ print(url.query.get_all("c"))
111
+ # ['4', 'x', '5']
112
+ print("b" in url.query, len(url.query))
113
+ # True 3
114
+ print(url.query.as_str())
115
+ # b=2&a=3&c=4&c=x&c=5
116
+ print(url.query.as_str(sort=True))
117
+ # a=3&b=2&c=4&c=5&c=x
118
+ url.query.update({"b": 9}, token="abc") # replaces values of existing names
119
+ print(url.query.as_str())
120
+ # b=9&a=3&c=4&c=x&c=5&token=abc
121
+ url.query.sort() # persistent, unlike as_str(sort=True)
122
+ print(url.query.as_str())
123
+ # a=3&b=9&c=4&c=5&c=x&token=abc
124
+ ```
125
+
126
+ Blank values are kept, so parsing and re-rendering is lossless:
127
+ `Params("a=&b=1").as_str()` is `"a=&b=1"` again.
128
+
129
+ `Params` can also be used on its own, e.g. with a `;` separator as used
130
+ for path parameters:
131
+
132
+ ```python
133
+ from action0.url import Params
134
+
135
+ params = Params({"foo": "bar", "a": ["b", "c"]}, separator=";")
136
+ print(params.as_str())
137
+ # foo=bar;a=b;a=c
138
+ ```
139
+
140
+ ## Building and comparing URLs
141
+
142
+ ```python
143
+ from action0.url import Url
144
+
145
+ # append path segments with "/" (always returns a new Url)
146
+ api = Url("https://example.com").origin() / "api" / "v2"
147
+ print(api / "users")
148
+ # https://example.com/api/v2/users
149
+
150
+ # resolve links like a browser does
151
+ print(Url("https://example.com/docs/intro.html").join("chapter2.html"))
152
+ # https://example.com/docs/chapter2.html
153
+
154
+ # derive variants without touching the original
155
+ url = Url("https://user:secret@example.com:8443/index.html")
156
+ print(url.copy(scheme="http", port=None))
157
+ # http://user:secret@example.com/index.html
158
+
159
+ # the authority ("hostname:port") and the origin as readable shortcuts
160
+ print(url.authority, "|", url.origin())
161
+ # example.com:8443 | https://example.com:8443
162
+
163
+ # equality compares the parts; query parameter order doesn't matter
164
+ print(Url("https://example.com?a=1&b=2") == Url("https://example.com?b=2&a=1"))
165
+ # True
166
+
167
+ # repr() never leaks the password (str() / as_str() keep it)
168
+ print(repr(url))
169
+ # Url(https://user:***@example.com:8443/index.html)
170
+ ```
171
+
172
+ ## Paths, normalization and encoding
173
+
174
+ ```python
175
+ from action0.url import Url
176
+
177
+ url = Url("https://example.com/docs/guide/intro.html?lang=en")
178
+ print(url.name, "|", url.suffix, "|", url.parent)
179
+ # intro.html | .html | https://example.com/docs/guide?lang=en
180
+ url.name = "outro.html"
181
+ print(url)
182
+ # https://example.com/docs/guide/outro.html?lang=en
183
+
184
+ # RFC 3986 style normalization: casing, default ports, dot segments
185
+ print(Url("https://example.com:443/a/./b/../c").normalize())
186
+ # https://example.com/a/c
187
+
188
+ # parts are stored decoded, rendering percent-encodes them again ...
189
+ url = Url("https://example.com/a%20b", fragment="§ 2")
190
+ print(url.path, "|", url)
191
+ # /a b | https://example.com/a%20b#%C2%A7%202
192
+
193
+ # ... and non-ASCII hostnames become punycode
194
+ print(Url(scheme="https", hostname="bücher.example"))
195
+ # https://xn--bcher-kva.example
196
+
197
+ print(url.is_absolute(), Url(path="/a").is_relative())
198
+ # True True
199
+ ```
200
+
201
+ For debugging and stdlib interoperability there are also `url.as_dict()`
202
+ (all parts as a plain dictionary) and `url.as_parse_result()` (the
203
+ `urllib.parse.ParseResult` named tuple).
204
+
205
+ ## Development
206
+
207
+ The project is managed with [uv](https://docs.astral.sh/uv/); `uv run`
208
+ creates and syncs the virtual environment automatically:
209
+
210
+ ```shell
211
+ uv run pytest # run the tests (incl. the docstring examples as doctests)
212
+ uv run ruff check # lint
213
+ uv run ruff format # format
214
+ uv run mypy # type-check (also: uv run pyright, uv run ty check)
215
+
216
+ # build the docs (Sphinx; deployed to GitHub Pages on push to main)
217
+ uv run --group docs sphinx-build -W docs docs/_build/html
218
+ ```
219
+
220
+ ### Releasing
221
+
222
+ The version lives only in `src/action0/url/__init__.py` (`__version__`).
223
+ To release: bump it, merge to `main`, then tag the release commit and push
224
+ the tag — the release workflow re-runs all checks, verifies the tag
225
+ matches `__version__`, builds sdist + wheel and publishes to PyPI via
226
+ trusted publishing:
227
+
228
+ ```shell
229
+ git tag v0.1.0
230
+ git push origin v0.1.0
231
+ ```
232
+
233
+ ## AI-assisted development
234
+
235
+ In the spirit of transparency: most of this project's code, tests and
236
+ documentation are written by [Claude Code](https://claude.com/claude-code),
237
+ Anthropic's coding agent — under human direction and review. The designs
238
+ are specified, discussed and iterated by a human, and every change is
239
+ reviewed before it lands in `main` or in a release. AI-authored commits
240
+ carry a `Co-Authored-By: Claude ...` trailer.
241
+
242
+ ## About action0
243
+
244
+ This is just the namespace I like to use for my personal projects.
245
+ I quite like namespaces.
@@ -0,0 +1,8 @@
1
+ action0/url/__init__.py,sha256=CiaJdt1FN1zI1A6lOC7GBu2bdf9I-zdaM3jtrNuDs-c,106
2
+ action0/url/base.py,sha256=2sNLMUPqlHiF2nA4J4V7rAlArxMbp_hgtoBkbMTe7x0,17874
3
+ action0/url/params.py,sha256=fuB7kZPZBingP4Od1Vpc2caGANTFiByVRZdDly72mKo,15409
4
+ action0/url/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ action0_url-0.1.0.dist-info/METADATA,sha256=NrzhZGvJG62NcRryOWV0DqeGWGLo9Bg0V9QsqbcpQoE,7798
6
+ action0_url-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ action0_url-0.1.0.dist-info/licenses/LICENSE,sha256=fpFAPtxX-2QkesT2Gw2CAN1CI1upb9I9zHANY77Z_rI,1066
8
+ action0_url-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LaughInJar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.