How to create a 8 digit Unique ID in Python?

有些话、适合烂在心里 提交于 2020-01-02 02:38:07

问题


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.


回答1:


Well you could use uuid.hex

import uuid
uuid.uuid4().hex[:8]

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).lower()



回答2:


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'


来源:https://stackoverflow.com/questions/42703059/how-to-create-a-8-digit-unique-id-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!