fix: 修改 random_string 方法,支持只生成随机数字

pull/9159/head
Bai 2 years ago committed by Jiangjie.Bai
parent 1bc4c1aef0
commit 2401c241f2

@ -18,25 +18,35 @@ def random_ip():
return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff))) return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
def random_string(length, lower=True, upper=True, digit=True, special_char=False): def random_string(length: int, lower=True, upper=True, digit=True, special_char=False):
chars = string.ascii_letters args_names = ['lower', 'upper', 'digit', 'special_char']
if digit: args_values = [lower, upper, digit, special_char]
chars += string.digits args_string = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string_punctuation]
args_string_map = dict(zip(args_names, args_string))
kwargs = dict(zip(args_names, args_values))
kwargs_keys = list(kwargs.keys())
kwargs_values = list(kwargs.values())
args_true_count = len([i for i in kwargs_values if i])
assert any(kwargs_values), f'Parameters {kwargs_keys} must have at least one `True`'
assert length >= args_true_count, f'Expected length >= {args_true_count}, bug got {length}'
can_startswith_special_char = args_true_count == 1 and special_char
chars = ''.join([args_string_map[k] for k, v in kwargs.items() if v])
while True: while True:
password = list(random.choice(chars) for i in range(length)) password = list(random.choice(chars) for i in range(length))
if upper and not any(c.upper() for c in password): for k, v in kwargs.items():
continue if v and not (set(password) & set(args_string_map[k])):
if lower and not any(c.lower() for c in password): # 没有包含指定的字符, retry
continue break
if digit and not any(c.isdigit() for c in password): else:
continue if not can_startswith_special_char and password[0] in args_string_map['special_char']:
break # 首位不能为特殊字符, retry
continue
if special_char: else:
spc = random.choice(string_punctuation) # 满足要求终止 while 循环
i = random.choice(range(1, len(password))) break
password[i] = spc
password = ''.join(password) password = ''.join(password)
return password return password

Loading…
Cancel
Save