Generate a Unique String in Python/Django

后端 未结 10 2599
清酒与你
清酒与你 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:14

    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)
    

提交回复
热议问题