Almost all of the meager provide a shortened URL service, the principle is that a URL address according to a certain algorithm to generate a string, and then added to a short domain behind a new URL address, the database will be stored in this short address and the original address, when the user click on this new short address, The short address service reads the original address from the database based on a few strings following the short domain name and then jumps to the page.
For example, Sina's meager URL is http://t.cn/xxxxxxx t.cn is its domain name, followed by a 7-bit figure out the string.
Method One: Using the Hachiku custom algorithm
Because URLs that appear too long in text are messy, either by omitting the display or by using a short URL.
To make it easy to count clicks and content filtering at the same time. A method for generating short URL values is implemented.
To prevent your hash value from being cracked, you can add your own salt when generating MD5 values.
This will not break the original URL even until your code_map.
To make the results more random, save the second bit that is not used for Each loop into E. This will result in a smaller conflict rate.
#引入哈希库import Hashlib def get_md5 (s): s = S.encode (' UTF8 ') if isinstance (S, Unicode) else s M = hashlib.md5 ( ) M.update (s) return m.hexdigest () Code_map = (' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' H ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' X ', ' Y ', ' z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ') def get_hash_key (long_url): Hkeys = [] hex = GET_MD5 (l Ong_url) for I in Xrange (0, 4): n = Int (hex[i*8: (i+1) *8], +) v = [] e = 0 for J in Xra Nge (0, 5): x = 0x0000003d & n e |= ((0x00000002 & N) >> 1) << J V . Insert (0, code_map[x]) n = n >> 6 e |= n << 5 v.insert (0, Code_map[e & 0x0000003d]) Hkeys.appen D (". Join (v)) return Hkeys if __name__ = = ' __main__ ': Print Get_hash_key (' http://www.pythontab.com ')
Method Two: Using the Libsurl Library
Libsurl is a C and Python library for generating short URLs, supporting short URL service sites such as bit.ly and TinyURL.