Python实现url与短链相互转换的方法

[本文出自天外归云的博客园]

问题:将url转换成指定长度的短链,并支持短链还原

代码如下:

#!/usr/bin/python
# 实现url与短链相互转换的方法
import random

words = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
url_to_short = {}
short_to_url = {}
max_retry_times = 3

def gen_short(length:int):
  short = ""
  for i in range(length):
    short += words[random.randint(0,length)]
  return short

def from_url_to_short(url:str, length:int):
  if url in url_to_short:
    return url_to_short[url]
  short = gen_short(length)
  retry_times = 0
  while retry_times < max_retry_times and short in short_to_url:
    short = gen_short(length)
    retry_times += 1
  if short in short_to_url:
    return None
  url_to_short[url] = short
  short_to_url[short] = url
  return short

def from_short_to_url(short:str):
  if short not in short_to_url:
    return None
  return short_to_url[short]

short = from_url_to_short("http://www.baidu.com", 6)
print(short)
url = from_short_to_url(short)
print(url)

1. 生成短链的方法自己定义:实现一个简单的hash过程

2. 对hash冲突的判断和处理:自定义重试次数、再hash

posted @ 2022-07-07 17:14  天外归云  阅读(136)  评论(0编辑  收藏  举报