Skip to content

Minimal example of URL validation #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
venv*/
.mypy_cache/
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pydantic
typing_extensions
37 changes: 37 additions & 0 deletions validate.py
Original file line number Diff line number Diff line change
@@ -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()