Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Unique String in Python/Django

Tags:

python

django

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

The key will contain numbers and uppercase English letters:

  • AU1B7
  • Y56AX
  • M0K7A

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

In the most pythonic way possible, how can I do this?

like image 347
Yax Avatar asked Sep 25 '14 04:09

Yax


People also ask

How do you generate unique random strings?

There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.

How do you generate unique random numbers in Django?

randint() method is used to generate a random number between the start and stop.

How do you create a unique ID in Python?

uuid1() is defined in UUID library and helps to generate the random id using MAC address and time component. bytes : Returns id in form of 16 byte string. int : Returns id in form of 128-bit integer. hex : Returns random id as 32 character hexadecimal string.


3 Answers

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

like image 156
zzart Avatar answered Oct 17 '22 02:10

zzart


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))
like image 25
Michael Stachura Avatar answered Oct 17 '22 02:10

Michael Stachura


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)
like image 25
Reza Abbasi Avatar answered Oct 17 '22 02:10

Reza Abbasi