The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a personal URL shortener in Python

Building a personal URL shortener in Python is a great project to practice web development, databases, and routing. Below is a minimal, functional version using Flask and SQLite. This basic version allows you to shorten URLs, store them in a database, and redirect to the original URL when the short URL is accessed.


Step-by-step: Personal URL Shortener using Flask and SQLite

✅ Requirements:

Install Flask and SQLite (SQLite comes preinstalled with Python):

bash
pip install flask

🔧 Project Structure:

pgsql
url_shortener/ │ ├── app.py └── templates/ ├── index.html └── result.html

📄 app.py

python
import string import random import sqlite3 from flask import Flask, request, redirect, render_template, url_for app = Flask(__name__) DATABASE = 'urls.db' def get_db(): conn = sqlite3.connect(DATABASE) conn.execute('CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, original TEXT, short TEXT)') return conn def generate_short_id(num_chars=6): return ''.join(random.choices(string.ascii_letters + string.digits, k=num_chars)) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': original_url = request.form['original_url'] conn = get_db() cursor = conn.cursor() # Check if URL already exists cursor.execute("SELECT short FROM urls WHERE original = ?", (original_url,)) row = cursor.fetchone() if row: short_id = row[0] else: short_id = generate_short_id() cursor.execute("INSERT INTO urls (original, short) VALUES (?, ?)", (original_url, short_id)) conn.commit() conn.close() return render_template('result.html', short_url=request.host_url + short_id) return render_template('index.html') @app.route('/<short_id>') def redirect_short_url(short_id): conn = get_db() cursor = conn.cursor() cursor.execute("SELECT original FROM urls WHERE short = ?", (short_id,)) row = cursor.fetchone() conn.close() if row: return redirect(row[0]) return f'Invalid URL: {short_id}', 404 if __name__ == '__main__': app.run(debug=True)

🧾 templates/index.html

html
<!DOCTYPE html> <html> <head> <title>URL Shortener</title> </head> <body> <h2>Shorten your URL</h2> <form method="post"> <input type="url" name="original_url" placeholder="Enter URL" required> <input type="submit" value="Shorten"> </form> </body> </html>

🧾 templates/result.html

html
<!DOCTYPE html> <html> <head> <title>Short URL</title> </head> <body> <h2>Your short URL is:</h2> <a href="{{ short_url }}">{{ short_url }}</a> </body> </html>

▶️ How to Run:

In your terminal:

bash
cd url_shortener python app.py

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


🛡️ Enhancements (Optional):

  • Add custom short URLs.

  • Use a better random string generator with collision checking.

  • Add analytics (click count, IP logging).

  • Use a production-grade database like PostgreSQL.

  • Deploy with Gunicorn + Nginx on a VPS or Heroku.

Would you like deployment instructions or enhancements like custom aliases or analytics tracking?

Share this Page your favorite way: Click any app below to share.

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

We respect your email privacy

Categories We Write About