From 556e38bbe074a38460ae822de02f34141e795283 Mon Sep 17 00:00:00 2001 From: "Haberman, Zachary" Date: Tue, 21 Jan 2025 13:47:30 -0800 Subject: [PATCH] Minimal example of URL validation --- .gitignore | 2 ++ requirements.txt | 2 ++ validate.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 .gitignore create mode 100644 requirements.txt create mode 100644 validate.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..21c4537 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +venv*/ +.mypy_cache/ \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c0c5da9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pydantic +typing_extensions \ No newline at end of file diff --git a/validate.py b/validate.py new file mode 100644 index 0000000..796f150 --- /dev/null +++ b/validate.py @@ -0,0 +1,37 @@ +# This isn't how I would maintain/manage python code, but is intended to show +# a minimum example of how you could use python to validate `predefined_url.json` +# Cheers! +# - ZH +"""Validate the JSON has valid URLs""" + +import json +from pathlib import Path +import sys +# Because I saw you're using 3.10, we use this. If 3.11+, use 'from typing import Self' +from typing_extensions import Self +from pydantic import BaseModel, HttpUrl + +class PredefinedUrl(BaseModel): + """Predefined URL Entry""" + url: HttpUrl + + + + @classmethod + def from_file(cls, file: Path) -> list[Self]: + """Load a list of predefined URLs from file""" + with file.open("r", encoding="utf8") as handle: + data: list[dict[str, str]] = json.load(handle) + return [cls.model_validate(x) for x in data] + +def main() -> None: + """Program main entry point""" + predefined_url = Path(sys.argv[1]) + if not predefined_url.is_file(): + raise FileNotFoundError(f"Could not find {predefined_url=}") + model = PredefinedUrl.from_file(predefined_url) + print(f"Model is valid: {model=}") + + +if __name__ == "__main__": # pragma: no cover + main() \ No newline at end of file