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

Original: https://www.cnblogs.com/LanTianYou/p/16455419.html
Author: 天外归云
Title: Python实现url与短链相互转换的方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15733/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总