Generate a Unique String in Python/Django
My favourite is
import uuid
uuid.uuid4().hex[:6].upper()
If you using django you can set the unique constrain on this field in order to make sure it is unique. https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique
From 3.6 You can use secrets module to generate nice random strings. https://docs.python.org/3/library/secrets.html#module-secrets
import secrets
print(secrets.token_hex(5))
A more secure and shorter way of doing is using Django's crypto module.
from django.utils.crypto import get_random_string
code = get_random_string(5)
get_random_string()
function returns a securely generated random string, uses
secrets
module under the hood.
You can also pass allowed_chars
:
from django.utils.crypto import get_random_string
import string
code = get_random_string(5, allowed_chars=string.ascii_uppercase + string.digits)
Am not sure about any short cryptic ways, but it can be implemented using a simple straight forward function assuming that you save all the generated strings in a set:
import random
def generate(unique):
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
while True:
value = "".join(random.choice(chars) for _ in range(5))
if value not in unique:
unique.add(value)
break
unique = set()
for _ in range(10):
generate(unique)