OnlineJudge/utils/shortcuts.py

24 lines
932 B
Python
Raw Normal View History

import logging
2016-10-29 18:17:35 +00:00
import random
2016-11-19 04:32:23 +00:00
from django.utils.crypto import get_random_string
2016-11-19 04:32:23 +00:00
logger = logging.getLogger(__name__)
2016-10-29 18:17:35 +00:00
def rand_str(length=32, type="lower_hex"):
"""
2016-11-19 04:32:23 +00:00
生成指定长度的随机字符串或者数字, 可以用于密钥等安全场景
:param length: 字符串或者数字的长度
:param type: str 代表随机字符串num 代表随机数字
:return: 字符串
2016-10-29 18:17:35 +00:00
"""
if type == "str":
2016-11-19 04:32:23 +00:00
return get_random_string(length, allowed_chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
2016-10-29 18:17:35 +00:00
elif type == "lower_str":
2016-11-19 04:32:23 +00:00
return get_random_string(length, allowed_chars="abcdefghijklmnopqrstuvwxyz0123456789")
2016-10-29 18:17:35 +00:00
elif type == "lower_hex":
2016-11-19 04:32:23 +00:00
return random.choice("123456789abcdef") + get_random_string(length - 1, allowed_chars="0123456789abcdef")
2016-10-29 18:17:35 +00:00
else:
2017-01-23 08:01:56 +00:00
return random.choice("123456789") + get_random_string(length - 1, allowed_chars="0123456789")