Extract Query Parameters from Raw URLs without urllib
Building zero-dependency HTTP gateways requires parsing raw query parameters directly. Handlers isolate the query segment after `?`, split key-value pairs along `&` and `=`, decode percent-encoded hex sequences (`%20` to space, `+` to space), and group duplicate keys into lists 🌐🔗⚡.
def parse_raw_query(query_str):
out = {}
for pair in query_str.split("&"):
if not pair: continue
k, _, v = pair.partition("=")
v = v.replace("+", " ")
out.setdefault(k, []).append(v)
return {k: v if len(v) > 1 else v[0] for k, v in out.items()}
print(parse_raw_query("user=alice&filter=fast&tag=ai&tag=edge"))
# 6. Extract Query Parameters from Raw URLs without urllib In edge runtimes and ultra-minimal server frameworks, you don't always want to import heavy standard library modules or third-party packages just to extract two query values from an incoming HTTP request line 🛑. ```python # Raw URI Query Anatomy: # https://example.com/api?search=data%20structures&tag=py&tag=algo#section-2 # |-----------------------------------| # Query String # 1. Delimiter: Split on '?' (start) and '#' (fragment anchor). # 2. Key-Value Splitting: Split pairs on '&', then split key and value on '='. # 3. Percent Decoding: '%20' -> ' ', '+' -> ' ', '%3D' -> '='. ``` ### Edge Invariants 1. **Multi-Value Keys**: Standard HTML forms submit multiple checkboxes using identical names (`?color=red&color=blue`). A naive dictionary assignment overwrites `'red'` with `'blue'`. Production parsers accumulate duplicates into lists. 2. **Missing Value Grace**: When a flag parameter has no equal sign (e.g. `?debug`), assign an empty string `""` rather than failing on string unpacking 🌐🔗⚡. --- ### Interactive Pop-Quiz 🧠 #### What critical requirement exists when parsing query strings containing duplicate keys like `?tag=python&tag=async`? - [ ] The parser must aggregate repeated keys into an array/list instead of overwriting the previous value in the dictionary 🛡️ - [ ] Duplicate keys automatically trigger an HTTP 500 status code - [ ] The browser discards all duplicate parameters before transmission - [ ] Duplicate keys force the server to restart the TCP connection --- ### Practical Challenge 🎯 Implement `parse_query_params(url: str) -> dict` from scratch without importing `urllib`. Extract the query part (between `?` and `#`), unquote `%XX` hex codes and `+` to spaces, and parse `key=value` pairs. If a key appears multiple times, store its values in a list. Test with `'https://api.xicae.org/search?q=machine+learning&tag=python&tag=async&sort=desc'`, assert parsed values, and print result. <details> <summary>Solution</summary> ```python def unquote_percent(s: str) -> str: res = bytearray() i = 0 b = s.encode("utf-8") while i < len(b): if b[i : i + 1] == b"%" and i + 2 < len(b): try: val = int(b[i + 1 : i + 3], 16) res.append(val) i += 3 continue except ValueError: pass elif b[i : i + 1] == b"+": res.extend(b" ") i += 1 continue res.append(b[i]) i += 1 return res.decode("utf-8", errors="replace") def parse_query_params(url: str) -> dict: query_part = url.split("?", 1)[1] if "?" in url else url query_part = query_part.split("#", 1)[0] if "#" in query_part else query_part params = {} if not query_part: return params for pair in query_part.split("&"): if not pair: continue k, _, v = pair.partition("=") clean_k = unquote_percent(k) clean_v = unquote_percent(v) if clean_k in params: existing = params[clean_k] if isinstance(existing, list): existing.append(clean_v) else: params[clean_k] = [existing, clean_v] else: params[clean_k] = clean_v return params sample_url = "https://api.xicae.org/search?q=machine+learning&tag=python&tag=async&sort=desc" result = parse_query_params(sample_url) assert result["q"] == "machine learning" assert result["tag"] == ["python", "async"] assert result["sort"] == "desc" print(f"Parsed Query Parameters: {result}") ``` </details>