examples.26_url_value
Demonstrates how to parse and validate URLs using a transformation pipeline
built on ConstrainedValue.
This example shows:
- How to convert a string into a parsed
urllib.parse.ParseResult.- How to validate that the URL includes both a scheme and host.
- How failures produce
Status.EXCEPTIONwith a descriptive error message.
Run directly:
python examples/26_url_value.py
Expected output:
ok : OK https://example.com/path?q=1 bad: EXCEPTION missing scheme or host
1"""Demonstrates how to parse and validate URLs using a transformation pipeline 2built on :class:`ConstrainedValue`. 3 4This example shows: 5 * How to convert a string into a parsed `urllib.parse.ParseResult`. 6 * How to validate that the URL includes both a scheme and host. 7 * How failures produce `Status.EXCEPTION` with a descriptive error message. 8 9Run directly: 10 11 python examples/26_url_value.py 12 13Expected output: 14 15 ok : OK https://example.com/path?q=1 16 bad: EXCEPTION missing scheme or host 17""" 18 19import sys 20import pathlib 21from typing import List 22from urllib.parse import urlparse, ParseResult 23 24# --------------------------------------------------------------------------- 25# Make repo root importable when running this file directly 26# --------------------------------------------------------------------------- 27sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) 28 29from constrained_values import Response, Status, TypeValidationStrategy 30from constrained_values.value import TransformationStrategy, ConstrainedValue, PipeLineStrategy 31 32 33class ToURL(TransformationStrategy[str, ParseResult]): 34 """Transform a string into a parsed URL using `urllib.parse.urlparse`.""" 35 36 def transform(self, value: str) -> Response[ParseResult]: 37 """Parse and validate the URL string. 38 39 Args: 40 value: The input string representing a URL. 41 42 Returns: 43 Response[ParseResult]: 44 * `Status.OK` and parsed `ParseResult` if the URL includes 45 a valid scheme and host. 46 * `Status.EXCEPTION` and a message if missing scheme or host. 47 """ 48 p = urlparse(value) 49 if not p.scheme or not p.netloc: 50 return Response(Status.EXCEPTION, "missing scheme or host", None) 51 return Response(Status.OK, "parsed", p) 52 53 54class HttpURL(ConstrainedValue[ParseResult]): 55 """A constrained value that parses and validates URLs.""" 56 57 def get_strategies(self) -> List[PipeLineStrategy]: 58 """Return the URL parsing and validation pipeline.""" 59 return [TypeValidationStrategy(str), ToURL()] 60 61 62def main() -> None: 63 """Run the URL validation demonstration. 64 65 Creates two :class:`HttpURL` instances — one valid and one invalid — and 66 prints their resulting status and details. 67 68 Steps: 69 1. Valid URL → OK, printed as full URL string. 70 2. Invalid URL → EXCEPTION, printed with error details. 71 72 Prints: 73 * `"ok : OK https://example.com/path?q=1"` 74 * `"bad: EXCEPTION missing scheme or host"` 75 """ 76 ok = HttpURL("https://example.com/path?q=1") 77 bad = HttpURL("not-a-url") 78 79 if ok.ok: 80 parsed = ok.value 81 print("ok :", ok.status.name, parsed.geturl()) 82 else: 83 print("ok :", ok.status.name, ok.details) 84 85 print("bad:", bad.status.name, bad.details) 86 87 88if __name__ == "__main__": 89 main()
class
ToURL(constrained_values.value.TransformationStrategy[str, urllib.parse.ParseResult]):
34class ToURL(TransformationStrategy[str, ParseResult]): 35 """Transform a string into a parsed URL using `urllib.parse.urlparse`.""" 36 37 def transform(self, value: str) -> Response[ParseResult]: 38 """Parse and validate the URL string. 39 40 Args: 41 value: The input string representing a URL. 42 43 Returns: 44 Response[ParseResult]: 45 * `Status.OK` and parsed `ParseResult` if the URL includes 46 a valid scheme and host. 47 * `Status.EXCEPTION` and a message if missing scheme or host. 48 """ 49 p = urlparse(value) 50 if not p.scheme or not p.netloc: 51 return Response(Status.EXCEPTION, "missing scheme or host", None) 52 return Response(Status.OK, "parsed", p)
Transform a string into a parsed URL using urllib.parse.urlparse.
37 def transform(self, value: str) -> Response[ParseResult]: 38 """Parse and validate the URL string. 39 40 Args: 41 value: The input string representing a URL. 42 43 Returns: 44 Response[ParseResult]: 45 * `Status.OK` and parsed `ParseResult` if the URL includes 46 a valid scheme and host. 47 * `Status.EXCEPTION` and a message if missing scheme or host. 48 """ 49 p = urlparse(value) 50 if not p.scheme or not p.netloc: 51 return Response(Status.EXCEPTION, "missing scheme or host", None) 52 return Response(Status.OK, "parsed", p)
Parse and validate the URL string.
Arguments:
- value: The input string representing a URL.
Returns:
Response[ParseResult]: *
Status.OKand parsedParseResultif the URL includes a valid scheme and host. *Status.EXCEPTIONand a message if missing scheme or host.
class
HttpURL(constrained_values.value.ConstrainedValue[urllib.parse.ParseResult]):
55class HttpURL(ConstrainedValue[ParseResult]): 56 """A constrained value that parses and validates URLs.""" 57 58 def get_strategies(self) -> List[PipeLineStrategy]: 59 """Return the URL parsing and validation pipeline.""" 60 return [TypeValidationStrategy(str), ToURL()]
A constrained value that parses and validates URLs.
def
get_strategies(self) -> List[constrained_values.value.PipeLineStrategy]:
58 def get_strategies(self) -> List[PipeLineStrategy]: 59 """Return the URL parsing and validation pipeline.""" 60 return [TypeValidationStrategy(str), ToURL()]
Return the URL parsing and validation pipeline.
Inherited Members
- constrained_values.value.ConstrainedValue
- ConstrainedValue
- status
- details
- value
- unwrap
- ok
def
main() -> None:
63def main() -> None: 64 """Run the URL validation demonstration. 65 66 Creates two :class:`HttpURL` instances — one valid and one invalid — and 67 prints their resulting status and details. 68 69 Steps: 70 1. Valid URL → OK, printed as full URL string. 71 2. Invalid URL → EXCEPTION, printed with error details. 72 73 Prints: 74 * `"ok : OK https://example.com/path?q=1"` 75 * `"bad: EXCEPTION missing scheme or host"` 76 """ 77 ok = HttpURL("https://example.com/path?q=1") 78 bad = HttpURL("not-a-url") 79 80 if ok.ok: 81 parsed = ok.value 82 print("ok :", ok.status.name, parsed.geturl()) 83 else: 84 print("ok :", ok.status.name, ok.details) 85 86 print("bad:", bad.status.name, bad.details)
Run the URL validation demonstration.
Creates two HttpURL instances — one valid and one invalid — and
prints their resulting status and details.
Steps:
- Valid URL → OK, printed as full URL string.
- Invalid URL → EXCEPTION, printed with error details.
Prints:
"ok : OK https://example.com/path?q=1""bad: EXCEPTION missing scheme or host"