Advanced · Web & APIs · Packages: standard library only
Project 22: URL Shortener Service
Build a URL shortener with sqlite storage, base62 short codes, 302 redirects, click statistics, URL validation and a self-test over a local server.
What you will learn
- Encode and decode integers with base62
- Store links in sqlite3 with parameterised queries
- Send redirects with the Location header
- Validate URLs with urllib.parse and run a self-testing server
Prerequisites
- Functions, loops and divmod
- sqlite3 basics (execute, commit)
- Classes
- http.server basics
- The json module
Packages and installation
Packages: standard library only.
Project structure
shortener/
main.py
urls.db (created when the program runs)Step-by-step build
- Choose the alphabet. Use 62 characters: digits, lowercase and uppercase letters.
- Write encode(). Repeatedly divmod the number by 62 and collect characters, then reverse them.
- Write decode(). Multiply the running number by 62 and add each character's index.
- Validate URLs. valid_url() accepts only http and https URLs that have a host name.
- Create the Store class. It opens sqlite, creates the links table and offers add(), visit() and stats().
- Build the handler. POST /shorten returns a code. GET /<code> sends a 302 redirect. GET /stats/<code> shows clicks.
- Write the demo. Start the server on port 0, send requests with http.client, then shut down.
- Check the database. Open urls.db afterwards with sqlite3 and look at the links table.
Complete source code
"""URL Shortener Service: sqlite storage, base62 codes, redirects and click counts."""
import http.client
import json
import os
import sqlite3
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
DB_FILE = "urls.db" # created in the current folder
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
ID_OFFSET = 125000 # makes the first codes look longer than one letter
def encode(number):
"""Turn an integer into a base62 string, e.g. 125001 -> 'ww9'."""
if number == 0:
return ALPHABET[0]
digits = []
while number:
number, rest = divmod(number, 62)
digits.append(ALPHABET[rest])
return "".join(reversed(digits))
def decode(code):
"""Reverse of encode(). Raises ValueError for characters outside the alphabet."""
number = 0
for char in code:
number = number * 62 + ALPHABET.index(char)
return number
def valid_url(url):
"""Accept only absolute http/https URLs that have a host name."""
try:
parts = urlparse(url)
except ValueError:
return False
return parts.scheme in ("http", "https") and bool(parts.netloc)
class Store:
"""All database work lives here, so the HTTP code stays simple."""
def __init__(self, path):
# check_same_thread=False because handler threads share this connection.
self.db = sqlite3.connect(path, check_same_thread=False)
self.lock = threading.Lock()
self.db.execute("""CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
clicks INTEGER NOT NULL DEFAULT 0)""")
self.db.commit()
def add(self, url):
"""Return the code for a URL. The same URL always gets the same code."""
with self.lock:
row = self.db.execute("SELECT id FROM links WHERE url = ?", (url,)).fetchone()
if row is None:
cur = self.db.execute("INSERT INTO links (url) VALUES (?)", (url,))
self.db.commit()
return encode(cur.lastrowid + ID_OFFSET), True
return encode(row[0] + ID_OFFSET), False
def visit(self, code):
"""Count a click and return the target URL (or None if unknown)."""
try:
link_id = decode(code) - ID_OFFSET
except ValueError:
return None
with self.lock:
row = self.db.execute("SELECT url FROM links WHERE id = ?", (link_id,)).fetchone()
if row:
self.db.execute("UPDATE links SET clicks = clicks + 1 WHERE id = ?", (link_id,))
self.db.commit()
return row[0] if row else None
def stats(self, code):
try:
link_id = decode(code) - ID_OFFSET
except ValueError:
return None
with self.lock:
return self.db.execute("SELECT url, clicks FROM links WHERE id = ?", (link_id,)).fetchone()
def make_handler(store):
class Handler(BaseHTTPRequestHandler):
def reply(self, status, payload=None, location=None):
body = json.dumps(payload or {}).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
if location:
self.send_header("Location", location)
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass
def do_POST(self):
if self.path != "/shorten":
return self.reply(404, {"error": "unknown path"})
length = int(self.headers.get("Content-Length", 0))
try:
url = json.loads(self.rfile.read(length)).get("url", "")
except (ValueError, AttributeError):
return self.reply(400, {"error": "invalid JSON"})
if not valid_url(url):
return self.reply(400, {"error": "url must start with http:// or https://"})
code, created = store.add(url)
self.reply(201 if created else 200, {"code": code, "short": f"/{code}"})
def do_GET(self):
if self.path.startswith("/stats/"):
row = store.stats(self.path[7:])
if row is None:
return self.reply(404, {"error": "unknown code"})
return self.reply(200, {"url": row[0], "clicks": row[1]})
target = store.visit(self.path.lstrip("/"))
if target is None:
return self.reply(404, {"error": "unknown code"})
self.reply(302, {"redirect": target}, location=target)
return Handler
def request(port, method, path, payload=None):
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
body = json.dumps(payload) if payload is not None else None
conn.request(method, path, body=body)
resp = conn.getresponse() # http.client never follows redirects
data = json.loads(resp.read())
location = resp.getheader("Location")
conn.close()
extra = f" Location={location}" if location else ""
print(f"{method:4} {path:<22} -> {resp.status} {data}{extra}")
return data
def main():
if os.path.exists(DB_FILE):
os.remove(DB_FILE) # start the demo with a clean database
store = Store(DB_FILE)
server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(store))
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
print("encode/decode check:", encode(125001), decode(encode(987654)))
try:
first = request(port, "POST", "/shorten", {"url": "https://example.com/a/very/long/path?x=1"})
request(port, "POST", "/shorten", {"url": "https://example.com/a/very/long/path?x=1"})
second = request(port, "POST", "/shorten", {"url": "http://example.org/"})
request(port, "POST", "/shorten", {"url": "ftp://bad.example/file"})
request(port, "GET", "/" + first["code"])
request(port, "GET", "/" + first["code"])
request(port, "GET", "/" + second["code"])
request(port, "GET", "/stats/" + first["code"])
request(port, "GET", "/stats/" + second["code"])
request(port, "GET", "/zzzzzz")
request(port, "GET", "/bad-code!")
finally:
server.shutdown()
server.server_close()
thread.join()
store.db.close()
print("Server stopped cleanly; data saved in", DB_FILE)
if __name__ == "__main__":
main()
Code explanation
Base62 codes
The row id plus an offset is converted to base62. Codes are short, stable and need no random numbers, so output is repeatable.
Same URL, same code
The url column is UNIQUE and add() looks for an existing row first, so shortening twice gives the same code (status 200 instead of 201).
Parameterised SQL
Queries use ? placeholders. This stops SQL injection and handles quotes in URLs.
Redirects
Status 302 plus a Location header tells browsers where to go. http.client does not follow it, so the demo can show it.
make_handler closure
The handler class is defined inside a function so it can use the store without global variables.
Expected output
encode/decode check: ww9 987654
POST /shorten -> 201 {'code': 'ww9', 'short': '/ww9'}
POST /shorten -> 200 {'code': 'ww9', 'short': '/ww9'}
POST /shorten -> 201 {'code': 'wwa', 'short': '/wwa'}
POST /shorten -> 400 {'error': 'url must start with http:// or https://'}
GET /ww9 -> 302 {'redirect': 'https://example.com/a/very/long/path?x=1'} Location=https://example.com/a/very/long/path?x=1
GET /ww9 -> 302 {'redirect': 'https://example.com/a/very/long/path?x=1'} Location=https://example.com/a/very/long/path?x=1
GET /wwa -> 302 {'redirect': 'http://example.org/'} Location=http://example.org/
GET /stats/ww9 -> 200 {'url': 'https://example.com/a/very/long/path?x=1', 'clicks': 2}
GET /stats/wwa -> 200 {'url': 'http://example.org/', 'clicks': 1}
GET /zzzzzz -> 404 {'error': 'unknown code'}
GET /bad-code! -> 404 {'error': 'unknown code'}
Server stopped cleanly; data saved in urls.db
Common errors and solutions
Solution: Open the connection with check_same_thread=False and guard it with a Lock.
Solution: ALPHABET.index() fails on unknown characters. Catch ValueError in visit() and stats() and return None.
Solution: Send Location with a full http(s) URL, and use 302 for temporary redirects.
Solution: The demo deletes urls.db at start. Remove that line if you want to keep data.
Ideas to improve the project
- Allow custom aliases chosen by the user
- Add expiry dates for links
- Rate limit requests per client
- Show a top-10 list of most clicked links
- Add an HTML form to create links