Generate a Unique String in Python/Django

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

    There is a function in django that does what you're looking for (credits to this answer):

    Django provides the function get_random_string() which will satisfy the alphanumeric string generation requirement. You don't need any extra package because it's in the django.utils.crypto module.

    >>> from django.utils.crypto import get_random_string
    >>> unique_id = get_random_string(length=32)
    >>> unique_id
    u'rRXVe68NO7m3mHoBS488KdHaqQPD6Ofv'
    

    You can also vary the set of characters with allowed_chars:

    >>> short_genome = get_random_string(length=32, allowed_chars='ACTG')
    >>> short_genome
    u'CCCAAAAGTACGTCCGGCATTTGTCCACCCCT'
    

提交回复
热议问题