47 – Real-World Python Projects – URL Shortener Service

This project builds a complete TinyURL-like service using Python + Flask.

Your URL shortener will be able to:

✔ Generate unique short URLs

✔ Redirect short URLs to original links

✔ Store all links in a database (CSV/SQLite)

✔ Prevent duplicate entries

✔ Track number of clicks (optional)

✔ Admin dashboard (optional)


🛠️ Technologies Used

  • Python (Flask)
  • SQLite / CSV
  • Hashing (base62)
  • HTML + Bootstrap

📁 Project Structure

url_shortener/
│── app.py
│── database.json
│── templates/
│     ├── index.html
│     ├── success.html
└── static/

🧩 1. Base62 Encoder (Creates Short Codes)

import string
chars = string.ascii_letters + string.digits

def encode(num):
    base = 62
    result = ""
    while num > 0:
        result = chars[num % base] + result
        num //= base
    return result

🧩 2. Flask App (app.py)

from flask import Flask, request, render_template, redirect
import json, os
from base62 import encode

app = Flask(__name__)

DB_FILE = "database.json"

def load_db():
    if not os.path.exists(DB_FILE):
        return {}
    with open(DB_FILE, "r") as f:
        return json.load(f)

def save_db(data):
    with open(DB_FILE, "w") as f:
        json.dump(data, f, indent=4)

@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        long_url = request.form["url"]
        db = load_db()

        # check duplicates
        for key, value in db.items():
            if value == long_url:
                return render_template("success.html", short=key)

        short_code = encode(len(db) + 1)
        db[short_code] = long_url
        save_db(db)

        return render_template("success.html", short=short_code)

    return render_template("index.html")

@app.route("/<code>")
def redirect_url(code):
    db = load_db()
    if code in db:
        return redirect(db[code])
    return "Invalid URL"

if __name__ == "__main__":
    app.run(debug=True)

🧩 3. index.html

<h1>URL Shortener</h1>

<form method="POST">
    <input type="text" name="url" placeholder="Enter URL" required>
    <button type="submit">Shorten</button>
</form>

🧩 4. success.html

<h2>Your Short URL:</h2>

<p>
    <a href="/{{ short }}" target="_blank">
        http://localhost:5000/{{ short }}
    </a>
</p>

<a href="/">Shorten another URL</a>

🚀 How to Run

pip install flask base62
python app.py

Open browser:

http://127.0.0.1:5000/

Comments

Leave a Reply

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