Coverage for centralnicreseller / apiconnector / idnaprocessor.py: 85%
27 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-21 15:25 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-21 15:25 +0000
1import idna
2import re
5class IDNAProcessor:
6 NON_TRANSITIONAL_TLDS = re.compile(
7 r"\.(?:art|be|ca|de|swiss|fr|pm|re|tf|wf|yt)\.?$"
8 )
10 @staticmethod
11 def is_transitional_processing(domain_name: str) -> bool:
12 """
13 Determines if the domain name's TLD should use transitional processing.
14 """
15 return bool(IDNAProcessor.NON_TRANSITIONAL_TLDS.search(domain_name))
17 @staticmethod
18 def to_ascii(domain_name, use_transitional=None):
19 if use_transitional is None:
20 use_transitional = IDNAProcessor.is_transitional_processing(domain_name)
21 try:
22 if use_transitional:
23 domain_name = idna.uts46_remap(domain_name, transitional=True)
24 return idna.encode(domain_name).decode("ascii")
25 except idna.IDNAError as e:
26 raise ValueError(f"Unable to translate {domain_name} to ASCII: {e}")
28 @staticmethod
29 def to_unicode(domain_name, use_transitional=None):
30 if use_transitional is None:
31 use_transitional = IDNAProcessor.is_transitional_processing(domain_name)
32 try:
33 if use_transitional:
34 return idna.decode(domain_name, uts46=True)
35 else:
36 return idna.decode(domain_name)
37 except idna.IDNAError as e:
38 raise ValueError(f"Unable to translate {domain_name} to Unicode: {e}")