Skip to content
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

feat: cache IANA TLDs for faster lookups #390

Merged
Merged
Changes from 2 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
33 changes: 25 additions & 8 deletions src/validators/domain.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,37 @@
"""Domain."""

# standard
import os
yozachar marked this conversation as resolved.
Show resolved Hide resolved
from pathlib import Path
import re
from typing import Generator, Optional, Set, Union
yozachar marked this conversation as resolved.
Show resolved Hide resolved

# local
from .utils import validator


def _iana_tld():
"""Load IANA TLDs as a Generator."""
# source: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
with Path(__file__).parent.joinpath("_tld.txt").open() as tld_f:
_ = next(tld_f) # ignore the first line
for line in tld_f:
yield line.strip()
class _TLDList:
"""Read IANA TLDs, and optionally cache them."""

cache: Optional[Set[str]] = None

@classmethod
def read_tlds_from_file(cls) -> Generator[str, None, None]:
# Try the most common TLDs before opening the file
yield from ("COM", "ORG", "RU", "DE", "NET", "BR", "UK", "JP", "FR", "IT")
with Path(__file__).parent.joinpath("_tld.txt").open() as tld_f:
_ = next(tld_f) # ignore the first line
for line in tld_f:
yield line.strip()

@classmethod
def tlds(cls) -> Union[Set[str], Generator[str, None, None]]:
if not cls.cache and os.environ.get("PYVLD_LOAD_TLD_TO_MEMORY") == "True":
cls.cache = set(_TLDList.read_tlds_from_file())
if cls.cache:
return cls.cache

return cls.read_tlds_from_file()
yozachar marked this conversation as resolved.
Show resolved Hide resolved


@validator
Expand Down Expand Up @@ -56,7 +73,7 @@ def domain(
if not value:
return False

if consider_tld and value.rstrip(".").rsplit(".", 1)[-1].upper() not in _iana_tld():
if consider_tld and value.rstrip(".").rsplit(".", 1)[-1].upper() not in _TLDList.tlds():
yozachar marked this conversation as resolved.
Show resolved Hide resolved
return False

try:
Expand Down