Custom URL Shortener

Prerequisites

Make sure you have Python installed, along with Flask and SQLite. You can install Flask via pip:

pip install Flask

Step 1: Set Up the Project Structure

Create a directory for your project, for example, url_shortener. Inside this directory, create the following files:

  • app.py
  • database.db (this will be created automatically)
  • templates/
    • index.html
    • result.html

Step 2: Create the Flask App (app.py)

Here’s a simple Flask app to handle URL shortening:

from flask import Flask, request, redirect, render_template
import sqlite3
import string
import random

app = Flask(__name__)

# Database setup
def init_db():
    with sqlite3.connect('database.db') as conn:
        conn.execute('''
            CREATE TABLE IF NOT EXISTS urls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                short_url TEXT UNIQUE,
                original_url TEXT NOT NULL
            )
        ''')
    conn.close()

# Generate a random string
def generate_short_url(length=6):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

# Route for the homepage
@app.route('/')
def index():
    return render_template('index.html')

# Route to shorten the URL
@app.route('/shorten', methods=['POST'])
def shorten():
    original_url = request.form['url']
    short_url = generate_short_url()

    with sqlite3.connect('database.db') as conn:
        conn.execute('INSERT INTO urls (short_url, original_url) VALUES (?, ?)', (short_url, original_url))
    conn.close()

    return render_template('result.html', short_url=short_url)

# Route to redirect to the original URL
@app.route('/<short_url>')
def redirect_to_url(short_url):
    with sqlite3.connect('database.db') as conn:
        cursor = conn.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
        row = cursor.fetchone()
    conn.close()

    if row:
        return redirect(row[0])
    else:
        return 'URL not found', 404

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

Step 3: Create the HTML Templates

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form action="/shorten" method="POST">
        <input type="text" name="url" placeholder="Enter URL" required>
        <button type="submit">Shorten</button>
    </form>
</body>
</html>

templates/result.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shortened URL</title>
</head>
<body>
    <h1>Your Shortened URL</h1>
    <p><a href="{{ short_url }}">{{ request.url_root }}{{ short_url }}</a></p>
    <a href="/">Shorten another URL</a>
</body>
</html>

Step 4: Run the Application

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

python app.py

Step 5: Access the Application

Open your web browser and go to http://127.0.0.1:5000/. You should see the URL shortener interface. Enter a URL, and it will provide you with a shortened version.


Comments

Leave a Reply

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