Create a Python script to implement a URL shortener using Flask.
- User
Create a Python script to implement a URL shortener using Flask.
- Assistant
Creating a URL shortener script
The user wants a Python script for a URL shortener using Flask. I think they’re looking for a minimal app with concise functionality. I’ll consider options like using an in-memory dictionary or SQLite for storage. An in-memory approach is simpler but temporary, while SQLite is better for persistence. I'll likely create a single-file app with an HTML template using either inline rendering or a static file, ensuring it can handle URL shortening, redirects, and basic validation.Designing a simple URL shortener
Since the user didn’t specify anything about persistence, the simplest solution is an in-memory mapping, which works well. I’ll use Flask and show how to run it. First, the user needs to install Flask with
pip install flask.The implementation will consist of an
app.pyscript that includes functions for generating a unique short ID and managing URL mappings. I'll also userender_template_stringfor a simple form and the results. The app will handle URL input, error checking, and mapping to a short ID.Completing the URL shortener scriptFor handling URL shortener logic, I’ll search the
url_mapfor existing values. When a new URL is provided, a unique short ID gets generated, mapping it to the original URL. I’ll construct the short URL and display it alongside the submitted form on a simple HTML page.The app will also handle redirects and manage 404 errors. I'll make sure to provide minimal usage instructions, emphasizing security and proper implementation, while keeping explanations brief and focused on running the app.Creating the HTML template for the URL shortener
I need to ensure the HTML string uses Jinja templating and to pass variables correctly. I’m crafting a simple HTML structure for the URL shortener, including a title, a form for URL input, and a section to display any errors.
I’ll also show the shortened URL if it exists and list any previously shortened URLs. I can rely on Flask to automatically include the
requestobject in the template context, making it easy to generate the full URL from the short ID. I'll return everything properly usingrender_template_string.Finalizing the URL shortener codeIn my implementation, I’m passing
short_url=Noneduring the initial GET request. To avoid re-submission, I’m planning to use the POST/Redirect/GET pattern, but I can keep it simpler by highlighting the use ofurl_for. Withurl_for, I can generate a complete URL for the dynamic short ID by using_external=True.I’ll also code to check for existing mappings to prevent duplicates, but generating a new mapping each time will be fine as well. I’ll wrap everything in a concise code block along with minimal instructions for running it. ```python
app.py
from flask import Flask, request, redirect, render_template_string, url_for, abort import string import random
app = Flask(name)
In-memory mapping: short_id -> original_url
url_map = {}
Characters used to build short IDs
CHARS = string.ascii_letters + string.digits
def generate_short_id(length: int = 6) -> str: """Generate a random, unique short ID.""" while True: short_id = ''.join(random.choice(CHARS) for _ in range(length)) if short_id not in url_map: return short_id
HTML_TEMPLATE = """
{% if error %} <p style="color: red;">{{ error }}</p> {% endif %} <form method="post"> <input type="text" name="url" size="60" placeholder="Enter a long URL" required> <button type="submit">Shorten</button> </form> {% if short_url %} <p> Short URL: <a href="{{ short_url }}" target="_blank">{{ short_url }}</a> </p> {% endif %} {% if urls %} <h2>Existing Short URLs (in this server run)</h2> <ul> {% for sid, long_url in urls.items() %} <li> <a href="{{ url_for('redirect_to_url', short_id=sid, _external=True) }}" target="_blank"> {{ url_for('redirect_to_url', short_id=sid, _external=True) }} </a> → {{ long_url }} </li> {% endfor %} </ul> {% endif %}@app.route('/', methods=['GET', 'POST']) def index(): short_url = None error = None
if request.method == 'POST': original_url = request.form.get('url', '').strip() if not original_url: error = "Please provide a URL." else: # Prepend scheme if missing, so redirects work correctly if not original_url.startswith(('http://', 'https://')): original_url = 'http://' + original_url # Optional: reuse existing short ID if URL is already shortened for sid, url in url_map.items(): if url == original_url: short_id = sid break else: short_id = generate_short_id() url_map[short_id] = original_url short_url = url_for('redirect_to_url', short_id=short_id, _external=True) return render_template_string( HTML_TEMPLATE, short_url=short_url, error=error, urls=url_map )@app.route('/<short_id>') def redirect_to_url(short_id): original_url = url_map.get(short_id) if original_url is None: abort(404) return redirect(original_url)
@app.errorhandler(404) def not_found(e): return "Short URL not found.", 404
if name == 'main': # Debug mode for development; disable or set to False in production app.run(debug=True)
Run it: ```bash pip install flask python app.pyThen open
http://127.0.0.1:5000/in your browser, enter a long URL, and you’ll get a short URL likehttp://127.0.0.1:5000/abc123that redirects to the original.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.