应用场景
最近在做一个web 项目的时候,突然想到一个问题:详情页的 url 上带有主键 id 号,这样的话别人就很容易抓取了。连列表页都不用爬,直接用 id 号自增就可以抓取所有的内容。那么,该如何解决这个问题?
突然间,想到了前二年用开发一个项目的时候,也遇到过类似的问题。那是一个电商项目,如果把 id 号呈现在 url 上面的话,就会暴露出很多问题,比如:商品数量、订单数量、用户数量等。当时,有朋友推荐了一个 ruby 库:。rails 下的配置为:gem 'hashids'。
那么,Python 库里有没有这个库?我搜索了一下,果真有。安装方法如下:
相关功能
刚在 pycharm 中测试了一下,挺不错的。功能也比较简单,如下:
# 实例化
hasher=hashids.Hashids(salt="secret_key")
hasher2=hashids.Hashids(salt="secret_key",min_length=5)
# 加密:
hasher.encode(1024*1024*1024)
hasher.encode(10,15,28)
# 解密:
hasher.decode("32BV73Y")
# 其他:
# 还可以自定义编码可称式,bash64、bash36等。
示例代码
直接上代码吧,这样更清晰一些:
importhashidsdeffoo1():hasher=hashids.Hashids(salt="secret_key")# 加密数字print(hasher.encode(1024*1024*1024))#=> 32BV73Y# 加密超长数字print(hasher.encode(324235445646457457457567575865868))# => 3zYaQd1ykYrwZVBRWWm91# 加密多个数字print(hasher.encode(10,15,28))#=> WeTdIm# 加密字符串print(hasher.encode("python")=="")#=> True# 解密print(hasher.decode("32BV73Y"))#=> (1073741824,)print(hasher.decode("WeTdIm"))#=> (10, 15, 28)deffoo2():hasher1=hashids.Hashids(salt="secret_key")hasher2=hashids.Hashids(salt="secret_key",min_length=5)print(hasher1.encode())#=> y5print(hasher1.encode(1))#=> beprint(hasher2.encode())#=> XMy5Mprint(hasher2.encode(1))#=> 2qbeJprint(hasher2.decode("XMy5M")[]==)#=> Truefoo1()foo2()
题外话
这是一个不错的库,能够在很多场景下适用。
不过需要注意的是,secret_key需要保存好,如果丢失的话,那么就无法解密了。
领取专属 10元无门槛券
私享最新 技术干货