如何將長地址URL轉換爲短地址URL,一個比較理想的解決方案就是使用發號器生成一個惟一的整數ID,而後轉換爲62進制,做爲短地址URL。python
發號器使用 Redis 的 incr 函數 incr('SID')
// 62個字符做爲62進制符號 0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ-_ 12345678 轉成 62 進製爲 RPGS
# python import redis class ShortenURL: _alphabet = '0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ-_' _base = len(_alphabet) def encode(self, number): string = '' while(number > 0): string = self._alphabet[number % self._base] + string number //= self._base return string def decode(self, string): number = 0 for char in string: number = number * self._base + self._alphabet.index(char) return number t = ShortenURL() # Redis 做爲ID發號器 r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0,password='hooyes') if r.exists('SID') != 1: r.set('SID',12345677) r.incr('SID') sid = int(r.get('SID')) # 生成短網址,假如域名爲 85.si sn = t.encode(sid) shorturl = 'https://85.si/' + sn print(shorturl) # 經過 ShortURL SN 解碼到原SID print(t.decode(sn))
本文爲hooyes原創首發於 hooyes.netredis
繼續閱讀全文函數