首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 互联网 >

余URL生成转换

2013-01-26 
短URL生成转换#encodingutf-8import stringimport redisimport hashlibLETTERS string.digits + string

短URL生成转换
#encoding=utf-8import stringimport redisimport hashlibLETTERS = string.digits + string.ascii_lettersLETTERS_NUM = len(LETTERS)COUNTER_KEY = 'url:counter'def init(rd,num): for i in xrange(LETTERS_NUM * num): rd.sadd('url:id:set',i)#通过urlid取得短url对应的字符串def get_url(urlid): result = [] q = urlid/LETTERS_NUM r = urlid%LETTERS_NUM result.append(LETTERS[r]) while q: r = q%LETTERS_NUM q = q/LETTERS_NUM result = [LETTERS[r]] + result return ''.join(result)#得到短url字符串def parse_url(rd, longurl): ret = longurl if (longurl.startswith("http://") or longurl.startswith("https://")) and len(longurl)>7: m = hashlib.md5() m.update(longurl) urlkey = m.digest() old_param = rd.get(urlkey) if old_param: ret = old_param else: urlid = int(rd.spop('url:id:set')) param = get_url(urlid) rd.incr(COUNTER_KEY, 1) rd.set(param,longurl) rd.set(urlkey,param) ret = param print "short url:",ret return retif __name__ == "__main__": url = "http://www.google.com/" rd = redis.Redis('127.0.0.1',6379,db=0) init(rd,3) parse_url(rd,url)

?

?

?

?

?

?

?

热点排行