URL Canonicalization Helper
Normalize scheme, host, port, dot segments, and query order while dropping tracking parameters, producing a stable cache key.
Code
import posixpath
from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
TRACKING_PREFIXES = ("utm_", "gclid", "fbclid")
def _normalize_host(hostname: str) -> str:
host = hostname.rstrip(".").lower()
if ":" in host:
return host
try:
return host.encode("idna").decode("ascii")
except UnicodeError as error:
raise ValueError(f"invalid hostname: {hostname}") from error
def canonicalize_url(raw: str) -> str:
parts = urlsplit(raw.strip())
scheme = parts.scheme.lower()
if scheme not in DEFAULT_PORTS:
raise ValueError(f"unsupported scheme: {scheme}")
if parts.hostname is None:
raise ValueError("url must include a host")
try:
port = parts.port
except ValueError as error:
raise ValueError(f"invalid port in {raw}") from error
host = _normalize_host(parts.hostname)
if ":" in host:
host = f"[{host}]"
netloc = host if port in (None, DEFAULT_PORTS[scheme]) else f"{host}:{port}"
path = posixpath.normpath(parts.path or "/")
if not path.startswith("/"):
path = "/" + path
encoded_path = quote(path, safe="/:@!$&'()*+,;=~-._%")
pairs = [
(key, value)
for key, value in parse_qsl(parts.query, keep_blank_values=True)
if not key.lower().startswith(TRACKING_PREFIXES)
]
pairs.sort()
return urlunsplit((scheme, netloc, encoded_path, urlencode(pairs), ""))
def main() -> None:
raw = "HTTPS://Example.COM.:443/Path/../Docs?b=2&a=1&utm_source=news#top"
print(canonicalize_url(raw))
print(canonicalize_url("http://example.com"))
print(canonicalize_url("https://b\u00fccher.example/stra\u00dfe?q=a b"))
try:
canonicalize_url("ftp://example.com/file")
except ValueError as error:
print("rejected:", error)
if __name__ == "__main__":
main()Inside the snippet
Under the hood: the functions _normalize_host, canonicalize_url and main.
Iteration happens inside for key, value in parse_qsl(parts.query, keep_blank_values=True) — everything outside it runs once. The import line is the dependency contract: parse_qsl, quote, urlencode, urlsplit, urlunsplit come from urllib and nothing else. ValueError appears at a raise inside an except handler — it fires only while that failure type is already being handled.
What to watch for
- Plan for an install step:
urllibandposixpathare a real dependency, resolved by the package manager. - The guard
scheme not in DEFAULT_PORTSshort-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
Entry signature: def canonicalize_url(raw: str) -> str
Running the file prints labeled results such as rejected: — each operation’s effect is visible in the output.
Running the file executes main, which drives canonicalize_url in order.
Core lines
def _normalize_host(hostname: str) -> str:
host = hostname.rstrip(".").lower()
if ":" in host:
return host
try:
return host.encode("idna").decode("ascii")
except UnicodeError as error:
raise ValueError(f"invalid hostname: {hostname}") from error
except ValueError as error:
raise ValueError(f"invalid port in {raw}") from error
except ValueError as error:
print("rejected:", error)
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
- Do I need to install anything before running this?
- Yes: `urllib` and `posixpath` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.