Categories We Write About

Build a URL shortener

Here’s a simple URL shortener implementation using Python (Flask) and SQLite. It allows users to input long URLs and get a short code they can use to redirect to the original URL.


πŸ”§ Tech Stack:

  • Python

  • Flask (web framework)

  • SQLite (lightweight database)

  • Hashlib (to create short codes)


πŸ“ Project Structure:

cpp
url_shortener/ β”‚ β”œβ”€β”€ app.py β”œβ”€β”€ templates/ β”‚ β”œβ”€β”€ index.html β”‚ └── redirect.html └── shortener.db (auto-created)

app.py – Main Flask Application

python
from flask import Flask, request, redirect, render_template, url_for import sqlite3 import hashlib app = Flask(__name__) DB = 'shortener.db' def init_db(): with sqlite3.connect(DB) as conn: conn.execute(''' CREATE TABLE IF NOT EXISTS urls ( id INTEGER PRIMARY KEY AUTOINCREMENT, original TEXT NOT NULL, short TEXT NOT NULL UNIQUE ) ''') init_db() def generate_short_code(url): return hashlib.md5(url.encode()).hexdigest()[:6] @app.route('/', methods=['GET', 'POST']) def index(): short_url = None if request.method == 'POST': original_url = request.form['url'] short_code = generate_short_code(original_url) short_url = request.host_url + short_code with sqlite3.connect(DB) as conn: cur = conn.cursor() cur.execute("SELECT * FROM urls WHERE short = ?", (short_code,)) data = cur.fetchone() if not data: cur.execute("INSERT INTO urls (original, short) VALUES (?, ?)", (original_url, short_code)) conn.commit() return render_template('index.html', short_url=short_url) @app.route('/<short_code>') def redirect_to_original(short_code): with sqlite3.connect(DB) as conn: cur = conn.cursor() cur.execute("SELECT original FROM urls WHERE short = ?", (short_code,)) result = cur.fetchone() if result: return redirect(result[0]) else: return render_template('redirect.html', message="Invalid or expired short URL.") if __name__ == '__main__': app.run(debug=True)

templates/index.html

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>URL Shortener</title> </head> <body> <h1>Simple URL Shortener</h1> <form method="POST"> <input type="url" name="url" placeholder="Enter long URL" required> <button type="submit">Shorten</button> </form> {% if short_url %} <p>Your shortened URL: <a href="{{ short_url }}" target="_blank">{{ short_url }}</a></p> {% endif %} </body> </html>

templates/redirect.html

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>URL Not Found</title> </head> <body> <h1>{{ message }}</h1> <a href="/">Go back</a> </body> </html>

βœ… How to Run

  1. Save files in a folder url_shortener/.

  2. Install Flask: pip install flask

  3. Run the app: python app.py

  4. Visit http://127.0.0.1:5000/ in your browser.

This simple tool generates a 6-character MD5-based short code for any URL and saves it in a SQLite DB. You can further enhance it with custom aliases, user auth, expiration, or analytics.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About