commit 90397715dcbfbe8274431bc7afdc9a2f17d12ed2
parent 9a49c9e5a3abf396d95ab7517437b58d4139de0d
Author: Sheng <webmaster0115@gmail.com>
Date: Tue, 21 Aug 2018 21:55:57 +0800
Optimized is_valid_hostname
Diffstat:
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/webssh/utils.py b/webssh/utils.py
@@ -1,13 +1,16 @@
import ipaddress
import re
-
try:
from types import UnicodeType
except ImportError:
UnicodeType = str
+numeric = re.compile(r'[0-9]+$')
+allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE)
+
+
def to_str(bstr, encoding='utf-8'):
if isinstance(bstr, bytes):
return bstr.decode(encoding)
@@ -43,17 +46,16 @@ def is_valid_port(port):
def is_valid_hostname(hostname):
- if hostname[-1] == ".":
+ if hostname[-1] == '.':
# strip exactly one dot from the right, if present
hostname = hostname[:-1]
if len(hostname) > 253:
return False
- labels = hostname.split(".")
+ labels = hostname.split('.')
# the TLD must be not all-numeric
- if re.match(r"[0-9]+$", labels[-1]):
+ if numeric.match(labels[-1]):
return False
- allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(label) for label in labels)