Programming/Python
[Python] shorten url (base64, url safe base64)
데이터현
2022. 4. 23. 20:54
URL에는 많은 정보가 담김. 그러다 보니 URL이 길어지는 문제가 발생 -> 불편하다! -> 이를 줄이기 위해 shorten url에 대한 고민이 생김
어떤 값을 Encode와 Decode를 하는 여러 가지 방법이 있는데,
알파벳과 로마자로 encode 하는 방식을 base62라고 함
1. a-z : 26개
2. A-Z : 26개
3. 0-9 : 10개
총합 : 62 그래서 base62
특수문자 2개 추가하면 base64 근데 여기 추가되는 두 개 특수문자가 + 와 /인데 이는 url에서 특별한 의미를 가지기 때문에 이렇게 쓰면 안 됨.
그래서 각각 - , _ 로 변환해준 게 base64 url-safe
아래 문제를 풀어봐도 좋겠다.
https://leetcode.com/problems/encode-and-decode-tinyurl/
Encode and Decode TinyURL - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
사용법
import base64
class Codec:
default_url = 'https://leetcode.com/'
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
str_encoded = base64.urlsafe_b64encode(bytes(longUrl, "UTF-8")).decode("UTF-8")
return self.default_url + str_encoded
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return base64.urlsafe_b64decode(bytes(shortUrl.split('/')[-1], "UTF-8")).decode("UTF-8")
잊지 말아야 하는 게 base64는 바이너리 형태로 인코딩하는 것임.
딕셔너리를 활용해서 풀면 아래처럼 풀면 깔끔
from random import choices
class Codec:
def __init__(self):
self.long_short = {}
self.short_long = {}
self.alphabet = "abcdefghijklmnopqrstuvwzyz"
def encode(self, longUrl):
while longUrl not in self.long_short:
code = "".join(choices(self.alphabet, k=6))
if code not in self.short_long:
self.short_long[code] = longUrl
self.long_short[longUrl] = code
return 'http://tinyurl.com/' + self.long_short[longUrl]
def decode(self, shortUrl):
return self.short_long[shortUrl[-6:]]
참조 :