Exemple #1
0
def shorten(url):
    """Shortens a given URL, returning the unique id of that URL

    :url: a valid URL string

    The URL will be recorded in the database if it does not already exist.

    Returns a string id composed of lowercase alphanumeric characters

    """
    existing_url = rdb.get('urls|' + url)

    if existing_url:
        return existing_url
    else:
        counter = rdb.incr('url_counter')
        short = int_to_base36(counter)
        rdb.set('urls|' + url, short)
        rdb.set('shorts|' + short, url)
        return short
Exemple #2
0
 def test_shorten_doesnt_exist_creates_new_next(self):
     rdb.set('url_counter', 51)
     shorten(TEST_URL)
     self.assertEqual(rdb.get('urls|' + TEST_URL), '1g')
     self.assertEqual(rdb.get('shorts|1g'), TEST_URL)
Exemple #3
0
 def test_shorten_doesnt_exist_creates_new(self):
     with self.assertRaises(KeyError):
         rdb['urls|' + TEST_URL]
     shorten(TEST_URL)
     self.assertEqual(rdb.get('urls|' + TEST_URL), '1')
     self.assertEqual(rdb.get('shorts|1'), TEST_URL)
Exemple #4
0
 def test_shorten_doesnt_exist_returns_valid(self):
     self.assertIsNone(rdb.get('urls|' + TEST_URL))
     self.assertEqual(shorten(TEST_URL), '1')