Create a Python script to implement a URL shortener using Flask.
- User
Create a Python script to implement a URL shortener using Flask.
Assistant
Designing the Architecture
I've been mapping out the core components of the URL shortener. Flask is the clear choice for the web server, and I need to figure out the best approach for storing and retrieving the shortened URLs. I'm leaning towards a database solution for persistence, but considering simpler in-memory options for initial prototyping. The design is coming into focus.
Considering Data Persistence
I've decided SQLite is the best choice for now, offering persistence without overcomplicating things. I've designed three core routes: a home route for input, a shortening logic route to handle submissions, and a redirect route to resolve short codes. The URL generation process will use random character strings. My focus now is on setting up the database and the supporting functions for generating short URLs.
Developing the Routes
I've sketched out the initial routes for the URL shortener. There's a home route to display the form, a
/shortenroute to handle submissions, and/with a short URL to handle the redirects. Now, I'm focusing on crafting the Flask code itself, keeping the logic as straightforward as possible, with SQLite as the database engine to maintain data across sessions.Building the Core Functions
I'm now fully immersed in coding the core functionality. I'm building a Flask application with the initial
appsetup and the vitalinit_dbfunction for SQLite. The short ID generation uses a combination of ASCII letters and digits, producing a 6-character short code. I've also set up the home route, handling both GET and POST requests, preparing to save the submitted URL to the database. The focus is on robustly saving submissions and rendering a response, and preparing the redirect route to use short IDs to retrieve the URL from the DB.Implementing Error Handling
I'm now integrating robust error handling, specifically for cases of invalid or missing URLs. I'm building form validation for empty entries and standardizing how URLs are processed to minimize unexpected issues. Furthermore, I've got to construct a clean, concise HTML template to provide a better user experience. Finally, I'm working to consolidate the final output, outlining all prerequisites, structuring the files properly, and offering clear instructions on running the application, while ensuring that the code adheres to best practices.
Refining Code Generation
I'm now integrating a retry mechanism into my short code generation to handle potential collisions, even though the probability is low. I've realized that using a dictionary for storage won't work long-term; SQLite is the better choice for data persistence and ease of integration. I'm focusing on assembling all the parts:
app.py,templates/index.html, and theinit_dblogic. Now I need to consider deployment, testing and any other final tweaks.Here is a complete, step-by-step implementation of a URL Shortener using Python, Flask, and SQLite (for storing the URLs permanently).
Prerequisites
You will need to install Flask. Open your terminal and run:
pip install flaskProject Structure
Create a folder for your project and set up the following file structure:
/url_shortener ├── app.py └── templates └── index.html
1. The Python Script (
app.py)This file handles the server logic, database connection, and key generation.
import sqlite3 import string import random from flask import Flask, render_template, request, redirect, url_for, flash, abort app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key_here' # Needed for flashing messages # --- Database Helper Functions --- def get_db_connection(): conn = sqlite3.connect('urls.db') conn.row_factory = sqlite3.Row # Allows accessing columns by name return conn def init_db(): """Initializes the database with the required table.""" conn = get_db_connection() with conn: conn.execute(''' CREATE TABLE IF NOT EXISTS urls ( id INTEGER PRIMARY KEY AUTOINCREMENT, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, original_url TEXT NOT NULL, short_id TEXT NOT NULL UNIQUE ); ''') conn.close() # --- Utility Functions --- def generate_short_id(length=6): """Generates a random string of characters.""" chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(length)) # --- Routes --- @app.route('/', methods=('GET', 'POST')) def index(): if request.method == 'POST': original_url = request.form['url'] if not original_url: flash('The URL is required!') return redirect(url_for('index')) # Simple check to ensure URL has scheme if not original_url.startswith(('http://', 'https://')): original_url = 'http://' + original_url conn = get_db_connection() # Check if URL already exists to save space (Optional logic) existing_url = conn.execute('SELECT short_id FROM urls WHERE original_url = ?', (original_url,)).fetchone() if existing_url: short_id = existing_url['short_id'] else: # Generate a unique short ID short_id = generate_short_id() while True: try: conn.execute('INSERT INTO urls (original_url, short_id) VALUES (?, ?)', (original_url, short_id)) conn.commit() break except sqlite3.IntegrityError: # Collision happened, generate a new ID and try again short_id = generate_short_id() conn.close() # Construct the full short URL to display short_url = request.host_url + short_id return render_template('index.html', short_url=short_url) return render_template('index.html') @app.route('/<short_id>') def redirect_to_url(short_id): conn = get_db_connection() url_data = conn.execute('SELECT original_url FROM urls WHERE short_id = ?', (short_id,)).fetchone() conn.close() if url_data: return redirect(url_data['original_url']) else: return abort(404) # Return a 404 Not Found error # --- Main Entry Point --- if __name__ == '__main__': init_db() # Initialize DB on first run app.run(debug=True)
2. The HTML Template (
templates/index.html)Create a folder named
templatesand add this file inside it. This provides the user interface.<!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> <style> body { font-family: sans-serif; max-width: 600px; margin: 50px auto; text-align: center; } input[type="text"] { width: 70%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; } button { padding: 10px 20px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #218838; } .result { margin-top: 30px; padding: 15px; background-color: #f0f0f0; border-radius: 5px; } .error { color: red; } </style> </head> <body> <h1>Python URL Shortener</h1> <!-- Flash Error Messages --> {% with messages = get_flashed_messages() %} {% if messages %} <div class="error"> {% for message in messages %} <p>{{ message }}</p> {% endfor %} </div> {% endif %} {% endwith %} <!-- Input Form --> <form method="post"> <input type="text" name="url" placeholder="Paste your long URL here..." required> <button type="submit">Shorten</button> </form> <!-- Result Display --> {% if short_url %} <div class="result"> <p>Short URL created:</p> <h3><a href="{{ short_url }}" target="_blank">{{ short_url }}</a></h3> </div> {% endif %} </body> </html>
3. How to Run It
- Open your terminal/command prompt.
- Navigate to the folder containing
app.py. - Run the application:
python app.py - You will see output indicating the server is running (usually
Running on http://127.0.0.1:5000). - Open your web browser and go to
http://127.0.0.1:5000.
How it Works
- Database (
urls.db): The script automatically creates a local SQLite file. It has a tableurlsstoring the original link and the generated short code. - Short ID: The
generate_short_idfunction creates a random 6-character string (e.g.,aX9z1b). - Creation Route (
/): When you submit a URL, the script checks if it already exists. If not, it saves it to the database with a new short ID. It produces a link likehttp://127.0.0.1:5000/aX9z1b. - Redirect Route (
/<short_id>): When you visit the short link, Flask captures the ID from the URL, looks it up in the database to find theoriginal_url, and automatically redirects the browser there.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.