My Blog

My WordPress Blog

My Blog

My WordPress Blog

URL Shortener Application

Step 1: Set Up the Project Structure

Create a new directory for your project and create the following files and folders:

arduinoCopy codeurl_shortener/
│
├── app.py
├── database.py
├── templates/
│   └── index.html
└── static/
└── styles.css

Step 2: Create the Database Module

Create a file named database.py to handle the SQLite database:

pythonCopy codeimport sqlite3

def init_db():
"""Initialize the database."""
conn = sqlite3.connect('urls.db')
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS urls (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        original_url TEXT NOT NULL,
        short_url TEXT NOT NULL UNIQUE
    )
''')
conn.commit()
conn.close()
def add_url(original_url, short_url):
"""Add a URL to the database."""
conn = sqlite3.connect('urls.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO urls (original_url, short_url) VALUES (?, ?)', (original_url, short_url))
conn.commit()
conn.close()
def get_original_url(short_url):
"""Retrieve the original URL from the database."""
conn = sqlite3.connect('urls.db')
cursor = conn.cursor()
cursor.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
result = cursor.fetchone()
conn.close()
return result[0] if result else None

Step 3: Create the Flask Application

Create a file named app.py and add the following code:

pythonCopy codefrom flask import Flask, request, redirect, render_template
import string
import random
import database

app = Flask(__name__)

# Initialize the database
database.init_db()

def generate_short_url(length=6):
"""Generate a random short URL."""
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(length))
@app.route('/', methods=['GET', 'POST']) def index():
if request.method == 'POST':
    original_url = request.form['url']
    short_url = generate_short_url()
    database.add_url(original_url, short_url)
    return render_template('index.html', short_url=short_url)
return render_template('index.html', short_url=None)
@app.route('/<short_url>') def redirect_to_url(short_url):
original_url = database.get_original_url(short_url)
if original_url:
    return redirect(original_url)
return "URL not found", 404
if __name__ == "__main__":
app.run(debug=True)

Step 4: Create the HTML Template

Create a file named index.html inside the templates folder and add the following code:

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;URL Shortener&lt;/title&gt;
&lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"&gt;
</head> <body>
&lt;div class="container"&gt;
    &lt;h1&gt;URL Shortener&lt;/h1&gt;
    &lt;form method="POST"&gt;
        &lt;input type="text" name="url" placeholder="Enter your URL here" required&gt;
        &lt;button type="submit"&gt;Shorten&lt;/button&gt;
    &lt;/form&gt;
    {% if short_url %}
        &lt;h2&gt;Short URL: &lt;a href="{{ short_url }}"&gt;{{ request.host_url }}{{ short_url }}&lt;/a&gt;&lt;/h2&gt;
    {% endif %}
&lt;/div&gt;
</body> </html>

Step 5: Create the CSS Styles

Create a file named styles.css inside the static folder and add the following code:

cssCopy codebody {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
} .container {
max-width: 600px;
margin: auto;
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
} h1 {
text-align: center;
} form {
display: flex;
flex-direction: column;
} input[type="text"] {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 5px;
} button {
padding: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
} button:hover {
background-color: #218838;
}

Step 6: Run the Application

  1. Open your terminal (or command prompt).
  2. Navigate to the directory where you saved the project.
  3. Run the application using the command:bashCopy codepython app.py
  4. Open your web browser and go to http://127.0.0.1:5000/.
URL Shortener Application

Leave a Reply

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

Scroll to top