osdict_project/spider/normalutils/utils/random.py

73 lines
1.9 KiB
Python

from typing import Callable
import random
from functools import wraps
from django.utils import timezone
def random_str(typename: str, randomlength: int = 16) -> Callable[[None], str]:
"""Parameter:
----------
type: 'common' [A-Za-z0-9]; 'lower' [a-z0-9]"""
common = "AaBbCcDdEeFfGgHhJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789"
lower = "abcdefghijklmnopqrstuvwxyz0123456789"
if typename == 'common':
chars = common
elif typename == 'lower':
chars = lower
else:
raise ValueError
def _do() -> str:
length = len(chars) - 1
ret = "".join([chars[random.randint(0, length)] for _ in range(randomlength)])
return ret
return _do
def create_random_unique_str(rand_func: Callable[[None], str]):
time_string = None
list_string = []
def create_random(rand_func: Callable[[None], str]):
timestr = timezone.now().timestamp()
timestr = str(int(timestr))
ranstr = rand_func()
ret = timestr + ranstr
return ret, timestr
def get_unique_str():
nonlocal time_string
nonlocal list_string
while True:
ret, timestr = create_random(rand_func)
if time_string != timestr:
time_string = timestr
list_string = [ret]
return ret
else:
if ret not in list_string:
list_string.append(ret)
return ret
def decrator_func(func):
@wraps(func)
def _do():
return get_unique_str()
return _do
return decrator_func
# return get_unique_str
@create_random_unique_str(random_str('common', 2))
def default_nickname() -> str:
pass
@create_random_unique_str(random_str('lower', 1))
def default_version_unique_id() -> str:
pass