Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a 8 digit Unique ID in Python?

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.

like image 509
RyuCoder Avatar asked Mar 09 '17 18:03

RyuCoder


People also ask

How do you generate a 6 digit unique ID in Python?

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.

How do you create a unique identifier?

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.

What is unique ID in Python?

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)


2 Answers

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)
like image 118
Aamir Rind Avatar answered Oct 07 '22 16:10

Aamir Rind


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'
like image 34
Roland Smith Avatar answered Oct 07 '22 18:10

Roland Smith