Generate a Unique String in Python/Django

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

    If you can afford to lose '8' and '9' in the generated numbers there is a very pythonic solution to getting a truly random number.

    import os
    import base64
    
    base64.b32encode(os.urandom(3))[:5].decode('utf-8')
    

    Since you are going for uniqueness then you have a problem since 36 * 36 * 36 * 36 * 36 = 60'466'176 which will definitely result in collisions if you have millions. Since sets are faster than dicts we do...

    some_dict = set()
    
    def generate():
        return base64.b32encode(os.urandom(3))[:5].decode('utf-8')
    
    def generate_unique():
        string = generate()
        while string not in some_set:
            string = generate()
        some_set.add(string)
        return string
    
    0 讨论(0)
  • 2020-12-15 06:02

    To generate unique one you can use below command:

    import uuid 
    str(uuid.uuid1())[:5]
    
    0 讨论(0)
  • 2020-12-15 06:05

    My favourite is

    import uuid 
    uuid.uuid4().hex[:6].upper()
    

    If you using django you can set the unique constrain on this field in order to make sure it is unique. https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.unique

    0 讨论(0)
  • 2020-12-15 06:09

    Am not sure about any short cryptic ways, but it can be implemented using a simple straight forward function assuming that you save all the generated strings in a set:

    import random
    
    def generate(unique):
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
        while True:
            value = "".join(random.choice(chars) for _ in range(5))
            if value not in unique:
                unique.add(value)
                break
    
    unique = set()
    for _ in range(10):
        generate(unique)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题