我要检查我收到的access_token
仅基于
SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
什么是最好的检查方法。我签出了re
,但我认为这并不重要。
我可以构建一个检查它的功能,但感兴趣的是是否有一个班轮可以做到这一点
is_build_from_salt_chars_only(token) -> returns bool true/false
示例:
a8B4
-> true
a8#4
-> false
答案 0 :(得分:2)
扩展@deceze的提示:
def is_build_from_salt_chars_only(token):
return set(token).issubset(set(SALT_CHARS))
答案 1 :(得分:1)
您可以尝试这样的事情:
def is_built_from_salt_chars_only(token):
return all(char in SALT_CHARS for char in token)
答案 2 :(得分:1)
如果您的Salt字符都是字母数字,那么最简单的方法是使用str
函数.isalnum()
:
salt = "adeooAEDjifewOfej23923mklEWE"
non_salt = "\dekoS,"
print(salt.isalnum())
# prints True
print(non_salt.isalnum())
# prints False
还有2种可能性:
SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
salt = "adeooAEDjifewOfej23923mklEWE"
non_salt = "\dekoS,"
# either with sets:
print(set(salt).issubset(set(SALT_CHARS)))
# prints True
print(set(non_salt).issubset(set(SALT_CHARS)))
# prints False
# or with a list comprehension:
print(all([x in SALT_CHARS for x in salt]))
# prints True
print(all([x in SALT_CHARS for x in non_salt]))
# prints False
答案 3 :(得分:1)
绝对是实现此目标的一种方法。请尝试以下操作:
SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def is_build_from_salt_chars_only(token):
if re.match('^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]+$', token, flags=0):
return True
else:
return False
print(is_build_from_salt_chars_only('a8B4'))
print(is_build_from_salt_chars_only('a8#4'))
如下所述,给出的SALT_CHARS意味着您可以使用更简洁的方法:
re.match(r'^\w+$', token, flags=0)
答案 4 :(得分:0)
这应该有效:
import re
SALT_CHARS = '^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*$'
def salt(tested_string):
return re.match(SALT_CHARS, tested_string) is not None
。
print(salt('asdf657'))
#returns true
print(salt('asdf6!57'))
#returns false
答案 5 :(得分:0)
可能有一种聪明而有效的方法:
salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
ascii = [ord(i) for i in a]
ascii.sort()
print(ascii)
[48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]
所以一种快速的方法是:
for i in 'ab#4':
if not 48 <= ord(i) < 57 and not 65 <= ord(i) <= 90 and not 97 <= ord(i) <= 122:
return False
return True
仅在SALT不变的情况下有效,因此您可以编码值以加快执行时间。