How do I create a URL shortener?

后端 未结 30 2045
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  盖世英雄少女心
    2020-11-22 05:27

    This is what I use:

    # Generate a [0-9a-zA-Z] string
    ALPHABET = map(str,range(0, 10)) + map(chr, range(97, 123) + range(65, 91))
    
    def encode_id(id_number, alphabet=ALPHABET):
        """Convert an integer to a string."""
        if id_number == 0:
            return alphabet[0]
    
        alphabet_len = len(alphabet) # Cache
    
        result = ''
        while id_number > 0:
            id_number, mod = divmod(id_number, alphabet_len)
            result = alphabet[mod] + result
    
        return result
    
    def decode_id(id_string, alphabet=ALPHABET):
        """Convert a string to an integer."""
        alphabet_len = len(alphabet) # Cache
        return sum([alphabet.index(char) * pow(alphabet_len, power) for power, char in enumerate(reversed(id_string))])
    

    It's very fast and can take long integers.

提交回复
热议问题