微薄短地址的實現-python

幾乎全部的微薄都提供了縮短網址的服務,其原理就是將一個url地址按照必定的算法生成一段字符串,而後加在一個短域名後面邊成了一個新的url地址,數 據庫中會存放這個短地址和原始的地址,當用戶點擊這個新的短地址後,短地址服務會根據短域名後面的幾個字符串從數據庫中讀出原來的地址而後頁面進行跳轉 。
好比新浪微薄中的url 是 http://t.cn/xxxxxxx  t.cn是其域名 ,其後面跟着的是7位算出來的字符串
http://www.guokr.com/question/297490/ 這個url 通過短地址算法後就成了 http://t.cn/zWCRWpM 

現將本身的算法提供出來 使用python語言實現 python

#!/usr/bin/env python
#coding=utf-8
import hashlib


chars = (
"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 shorten(origin):
key = "fuck-gfw.ooxx.shorten"
#對傳入網址進行MD5加密
hex = hashlib.md5(key + origin).hexdigest()
res = [0 for i in range(4)]
for i in range(4):
#把加密字符按照8位一組16進制與0x3FFFFFFF進行位與運算
hexint = 0x3FFFFFFF & int("0x" + hex[i * 8: i*8+8], 16)
outChars = ""
for j in range(7):
#把獲得的值與0x0000003D進行位與運算,取得字符數組chars索引
index = 0x0000003D & hexint
#把取得的字符相加
outChars += chars[index]
#每次循環按位右移5位
hexint = hexint >> 5
#把字符串存入對應索引的輸出數組
res[i] = outChars
return res

print shorten('http://www.google.com')
shorten(url) 這個方法會返回一個包含4個字符串的地址
上面代碼返回的將是

['3IJJ7va', '6ZZfUfa', 'YNJniia', 'UFVRzea'] 算法

那麼這個短地址的形式將是 http://oo.xx/ 3IJJ7va
相關文章
相關標籤/搜索