在Python/Django中生成一个唯一的字符串

Yax*_*Yax 14 python django

我想要的是为我的网站上的用户生成大小为5的字符串(键).更像是BBM PIN.

密钥将包含数字和大写英文字母:

  • AU1B7
  • Y56AX
  • M0K7A

即使我生成数百万字符串,我怎么能对字符串的唯一性保持静止?

尽可能以最蟒蛇的方式,我该怎么做?

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

  • 由于字母字符仅限于A..F,因此不会生成AU1B7,Y56AX和M0K7A.它也不会产生有保证的唯一值.您可以添加代码以显示如何处理冲突. (4认同)
  • 代码长度+1。但我很好奇你如何确定你正在产生独特的价值?它不会生成重复值吗? (2认同)

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)

  • 这会生成一个十六进制字符串。你实际上无法用它产生数百万(复数)。但你可以赚一百万。 (2认同)

Rez*_*asi 7

一种更安全、更短的方法是使用 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)