Creating a unique string in Python / Django

I want to create a string (key) of size 5 for my users on my website. More like a BBM PIN.

The key will contain numbers and letters in upper case:

  • AU1B7
  • Y56AX
  • M0K7A

How can I be at ease about the uniqueness of strings, even if I generate them in millions?

In the pythonic way itself, how can I do this?

+10
source share
4 answers

My favorite

import uuid uuid.uuid4().hex[:6].upper() 

If you are using django, you can set a unique delimiter in this field to make sure it is unique. https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique

+22
source

Not sure of any short cryptic ways, but it can be implemented using a simple direct function, which assumes that all generated lines are stored 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) 
+2
source
 size = 5 ''.join(random.choice(string.letters[26:] + string.digits) for in range(size)) 

this will generate some short code, but they can be duplicated. therefore, before saving, make sure that they are unique in your database.

 def generate(size=5): code = ''.join(random.choice(string.letters[26:] + string.digits) for in range(size)) if check_if_duplicate(code): return generate(size=5) return code 

or using a unique django restriction and exception handling.

+1
source

Starting from 3.6. You can use the secrets module to create nice random strings. https://docs.python.org/3/library/secrets.html#module-secrets

 import secrets print(secrets.token_hex(5)) 
0
source

Source: https://habr.com/ru/post/975812/


All Articles