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:
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?
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.
randint() method is used to generate a random number between the start and stop.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With