לדלג לתוכן

4.4 מקצר URLs תרגול

מימוש

תרגיל 1 - Base62

מימשו Base62Codec עם:
- encode(n: int) -> str - ממיר מספר לstring Base62
- decode(s: str) -> int - ממיר string Base62 למספר

בדקו:

codec = Base62Codec()
assert codec.encode(0) == "0"
assert codec.encode(61) == "Z"
assert codec.encode(62) == "10"
assert codec.decode(codec.encode(999999)) == 999999

תרגיל 2 - URL Shortener מלא

בנו URL Shortener פשוט עם:

class URLShortener:
    def __init__(self):
        self._db: dict[int, str] = {}   # id -> long_url
        self._cache: dict[str, str] = {}  # short_code -> long_url
        self._next_id = 1

    def shorten(self, long_url: str) -> str:
        """מחזיר short code"""
        ...

    def expand(self, short_code: str) -> str | None:
        """מחזיר long URL, None אם לא קיים"""
        ...

    def get_stats(self) -> dict:
        """מחזיר: total_urls, cache_size"""
        ...

בדיקה:

shortener = URLShortener()
code = shortener.shorten("https://www.example.com/very/long/path")
assert shortener.expand(code) == "https://www.example.com/very/long/path"
assert shortener.expand("nonexistent") is None

# אותה URL מחזירה אותו code
code2 = shortener.shorten("https://www.example.com/very/long/path")
assert code == code2

תרגיל 3 - שאלות עיצוב

  1. מדוע 302 עדיף על 301 אם רוצים analytics?
  2. מה יקרה אם השתמשנו ב-MD5 hash במקום ID+Base62 ויצרנו התנגשות? איך הייתם מטפלים בה?
  3. אם רוצים לתמוך ב-custom short codes (משתמש בוחר /mylink) - מה צריך לשנות בארכיטקטורה?