How to make unique short URL with Python?

后端 未结 12 1280
渐次进展
渐次进展 2020-12-02 07:02

How can I make unique URL in Python a la http://imgur.com/gM19g or http://tumblr.com/xzh3bi25y When using uuid from python I get a very large one. I want something shorter f

12条回答
  •  悲哀的现实
    2020-12-02 08:04

    My Goal: Generate a unique identifier of a specified fixed length consisting of the characters 0-9 and a-z. For example:

    zcgst5od
    9x2zgn0l
    qa44sp0z
    61vv1nl5
    umpprkbt
    ylg4lmcy
    dec0lu1t
    38mhd8i5
    rx00yf0e
    kc2qdc07
    

    Here's my solution. (Adapted from this answer by kmkaplan.)

    import random
    
    class IDGenerator(object):
        ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"
    
        def __init__(self, length=8):
            self._alphabet_length = len(self.ALPHABET)
            self._id_length = length
    
        def _encode_int(self, n):
            # Adapted from:
            #   Source: https://stackoverflow.com/a/561809/1497596
            #   Author: https://stackoverflow.com/users/50902/kmkaplan
    
            encoded = ''
            while n > 0:
                n, r = divmod(n, self._alphabet_length)
                encoded = self.ALPHABET[r] + encoded
            return encoded
    
        def generate_id(self):
            """Generate an ID without leading zeros.
    
            For example, for an ID that is eight characters in length, the
            returned values will range from '10000000' to 'zzzzzzzz'.
            """
    
            start = self._alphabet_length**(self._id_length - 1)
            end = self._alphabet_length**self._id_length - 1
            return self._encode_int(random.randint(start, end))
    
    if __name__ == "__main__":
        # Sample usage: Generate ten IDs each eight characters in length.
        idgen = IDGenerator(8)
    
        for i in range(10):
            print idgen.generate_id()
    

提交回复
热议问题