我想要的是为我的网站上的用户生成大小为5的字符串(键).更像是BBM PIN.
密钥将包含数字和大写英文字母:
即使我生成数百万字符串,我怎么能对字符串的唯一性保持静止?
尽可能以最蟒蛇的方式,我该怎么做?
zza*_*art 30
我最喜欢的是
import uuid
uuid.uuid4().hex[:6].upper()
Run Code Online (Sandbox Code Playgroud)
如果您使用django,您可以在此字段上设置唯一约束,以确保它是唯一的.https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique
Mic*_*ura 14
从 3.6 开始,您可以使用 secrets 模块生成漂亮的随机字符串。 https://docs.python.org/3/library/secrets.html#module-secrets
import secrets
print(secrets.token_hex(5))
Run Code Online (Sandbox Code Playgroud)
一种更安全、更短的方法是使用 Django 的加密模块。
from django.utils.crypto import get_random_string
code = get_random_string(5)
Run Code Online (Sandbox Code Playgroud)
get_random_string()函数返回一个安全生成的随机字符串,secrets在引擎盖下使用
模块。
您还可以通过allowed_chars:
from django.utils.crypto import get_random_string
import string
code = get_random_string(5, allowed_chars=string.ascii_uppercase + string.digits)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20769 次 |
| 最近记录: |