使用URL缩短器|短链接技术分享

2022-08-30 11:13:40

阅读 1521

使用URL缩短器|短链接技术分享

背景信息

我们什么时候使用URL缩短器?

在你的电脑生活中,你可能曾经见过这样的URL。

https://suowo.cn/3kiMhkU

如果我们想分享一个URL,有时会遇到这样的问题:它太长了,例如这个URL。

https://www.google.com/search?q=codewars&tbm=isch&ved=2ahUKEwjGuLOJjvjsAhXNkKQKHdYdDhUQ2-cCegQIABAA&oq=codewars&gs_lcp=CgNpbWcQAzICCAAyBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBggAEAUQHlDADlibD2CjEGgAcAB4AIABXIgBuAGSAQEymAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&sclient=img&ei=RJmqX8aGHM2hkgXWu7ioAQ&bih=1099&biw=1920#imgrc=Cq0ZYnAGP79ddM

在这种情况下,URL缩短器就非常有用。

它是如何工作的?

URL缩短器得到一个长的URL,然后将其转换为一个较短的URL。两个URL都存储在一个数据库中。重要的是,每个长的URL都被分配了一个独特的短的URL。

如果用户随后调用短网址,数据库将被检查,以确定哪个长网址属于这个短网址,并将您重定向到原始/长网址。

重要提示:有些URL,如www.google.com,使用非常频繁。可能会发生两个用户想缩短同一个URL的情况,所以你必须检查这个URL以前是否被缩短过,以节省数据库的内存。

任务 网址缩短

编写一个缩短方法,接收一个长的URL,并返回一个以short.ly/开头的短URL,只由小写字母组成(以及一个点和一个斜线),最大长度为13。

 

重定向URL

编写一个重定向方法,该方法接收缩短的URL并返回相应的长URL。

性能测试有475_000个随机测试。

short_url1 = url_shortener.shorten("https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f")
test.expect(test_format(short_url1), message="Wrong format!")

short_url2 = url_shortener.shorten("https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f")
test.expect(test_format(short_url2), message="Wrong format!")

test.assert_equals(short_url1, short_url2, message="Should work with same long URLs")

test.assert_equals(url_shortener.redirect(short_url1), "https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f")

你不需要一个复杂的算法来解决这个卡塔,但是每次通过整个数据库来迭代检查一个URL之前是否被使用过,或者根据随机性来生成短URL,都不会通过。祝你好运,玩得开心

from itertools import product
from string import ascii_lowercase


def short_url_generator():
    for l in range(1, 5):
        yield from ('short.ly/' + ''.join(p) for p in product(ascii_lowercase, repeat=l))


class UrlShortener:

    short_urls = short_url_generator()
    long_to_short = {}
    short_to_long = {}

    @classmethod
    def shorten(cls, long_url):
        if long_url in cls.long_to_short:
            return cls.long_to_short[long_url]

        short_url = next(cls.short_urls)
        cls.long_to_short[long_url] = short_url
        cls.short_to_long[short_url] = long_url
        return short_url

    @classmethod
    def redirect(cls, short_url):
        if short_url in cls.short_to_long:
            return cls.short_to_long[short_url]
        raise Exception('Redirection failed!')

Url_shortener = UrlShortener

工程类项目为重定向建立2个字典,key和value互为对应。

 

缩我,高速云服务器
实时掌握推广动态
让您深入了解用户,提高推广转化率
联系我们
    1. 电话:400-001-9255
      联系客服
      常见问题
  • 公众号
    客服微信