Creating a URL Shortener with Python & Flask

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated

 


Creating a URL Shortener with Python & Flask 🔗🚀

Introduction: Why Build a URL Shortener?

Long URLs can be difficult to share, remember, or use in social media posts. A URL shortener allows you to create short, user-friendly links that redirect to long URLs.

In this tutorial, we will build a simple URL shortener using Python & Flask. This project is great for beginners and covers:
Flask setup for web development
Database integration using SQLite
Generating short links for long URLs
Redirecting users to original URLs

By the end, you will have a fully functional URL shortener running on your system! 🚀


Step 1: Install Required Dependencies 🛠️

Before starting, ensure you have Python (3.11 recommended) installed. Then, install Flask:

pip install flask flask-sqlalchemy

We use:
Flask – For web development
Flask-SQLAlchemy – For database handling


Step 2: Set Up Flask Project Structure 📁

Create a project folder and structure it like this:

url_shortener/
│── app.py  
│── templates/  
│   ├── index.html  
│   ├── short_url.html  
│── static/  
│── database.db  

📌 Explanation:

  • app.py – Main Flask application
  • templates/ – Stores HTML files
  • static/ – For CSS/JS files
  • database.db – Stores shortened URLs

Step 3: Create the Flask App (app.py) 📝

Open app.py and start coding:

from flask import Flask, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
import random, string

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)

# Database model
class URL(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    long_url = db.Column(db.String(500), nullable=False)
    short_url = db.Column(db.String(10), unique=True, nullable=False)

# Generate a short URL
def generate_short_url():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=6))

# Homepage
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        long_url = request.form['long_url']
        short_url = generate_short_url()
        new_url = URL(long_url=long_url, short_url=short_url)
        db.session.add(new_url)
        db.session.commit()
        return render_template('short_url.html', short_url=short_url)
    return render_template('index.html')

# Redirect to original URL
@app.route('/<short_url>')
def redirect_to_url(short_url):
    url_entry = URL.query.filter_by(short_url=short_url).first()
    if url_entry:
        return redirect(url_entry.long_url)
    return "URL not found", 404

if __name__ == '__main__':
    db.create_all()  # Create database tables
    app.run(debug=True)

📌 How It Works:
✔ Stores original and shortened URLs in the database
✔ Generates random 6-character short URLs
✔ Redirects users to the original URL


Step 4: Create HTML Templates 🎨

1️⃣ index.html (Form to Enter Long URL)

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h2>Enter URL to Shorten</h2>
    <form method="POST">
        <input type="url" name="long_url" required>
        <button type="submit">Shorten</button>
    </form>
</body>
</html>

2️⃣ short_url.html (Displays Shortened URL)

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

Step 5: Run the Flask App 🚀

In your terminal, navigate to your project folder and run:

python app.py

Now, open http://127.0.0.1:5000/ in your browser and start shortening URLs! 🎉


Step 6: Deploy Your URL Shortener 🌍

To make your URL shortener public, you can:
✅ Deploy on Heroku using Flask
✅ Use PythonAnywhere for free hosting
✅ Deploy on Vercel or AWS


Conclusion: Build Your Own URL Shortener! 🚀

You have successfully created a working URL shortener using Python & Flask! 🎉

Full Flask web app with database
Short URL generation & redirection
Beginner-friendly and scalable

💡 Next Steps:

  • Add custom short URLs
  • Implement click tracking & analytics
  • Use MongoDB or PostgreSQL for scalability

🔥 Did you enjoy this project? Share your thoughts in the comments! 🔥

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.