hooyes

基于Redis作为发号器生成短网址Python实践

|2018-04-24

请尊重原创,本文原文地址:https://hooyes.net/p/python-redis-short-url

描述

如何将长地址URL转换为短地址URL,一个比较理想的解决方案就是使用发号器生成一个唯一的整数ID(这唯一ID与长网址一一对应),然后转换为62进制,作为短地址URL。

实现

发号器使用 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))

测试

运行 python redis-short.py 即可以测试

//注意需要具备 redis 

以上代码已放到Hooyes的Github上开源,欢迎Fork或提建议。

redis-short.py

评论

点击发表评论

$ welcome to hooyes.net
[INFO] ------------------------------o-
[INFO] Author : HOOYES
[INFO] Site : https://hooyes.net
[INFO] Page : https://hooyes.net/p/python-redis-short-url
[INFO] Last build : 2023-07-31 09:16:20 +0000
[INFO] -0------------------------------
原文地址:https://hooyes.net/p/python-redis-short-url
原文地址:https://hooyes.net/p/python-redis-short-url
Content
...
TOP