I am making a web app for practice, it is a job portal. I want to create 8 digit unique IDs for job which will be visible to the end user. Ids can have numbers and alphabets. Pattern needs to be 8 digits without hyphens or dashes like XXXXXXXX.
I know there is UUID thing in python. But they seem to generate the id in their specific format. Is there a way to get the id in my required format? If not can someone please guide me on how to go about it?
I know there is a similar thread How can I generate a unique ID in Python?; but it does not answer my question specifically. It did not answer what I was trying to achieve.
Thanks in advance.
Let's see how we can generate a random integer in Python: # Generating a random integer in Python import random print(random. randint(0,10)) # Returns: 6 Generate Random Numbers Between Two Values in Python. In the example above, we used 0 as the starting point.
The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.
All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. ( except for some object that has a constant unique id, like integers from -5 to 256)
Well you could use uuid.hex
import uuid
uuid.uuid4().hex[:8] # Might reduce uniqueness because of slicing
Or Django also has helper function get_random_string which accepts two parameters length
(default=12) and allowed_chars
:
from django.utils.crypto import get_random_string
get_random_string(8)
Use os.urandom
for the data, and base64
encode it;
In [1]: import os
In [2]: import base64
In [3]: base64.b64encode(os.urandom(6)).decode('ascii')
Out[3]: '6Amtry80'
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