Generate a Unique String in Python/Django

后端 未结 10 2606
清酒与你
清酒与你 2020-12-15 05:56

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:

10条回答
  •  清歌不尽
    2020-12-15 06:24

    size = 5
    ''.join(random.choice(string.letters[26:] + string.digits) for in range(size))
    

    this will generate some short code, but they can be duplicated. so check if they are unique in your database before saving.

    def generate(size=5):
        code = ''.join(random.choice(string.letters[26:] + string.digits) for in range(size))
        if check_if_duplicate(code):
            return generate(size=5)
        return code
    

    or using django unique constrain, and handle exceptions.

提交回复
热议问题