Creating a URL Shortener.

How To Make a URL Shortener with Flask and SQLite

Creating a URL Shortener.

Table of contents

No heading

No headings in the article.

Introduction: URL shorteners are convenient tools that transform long, cumbersome URLs into short and easy-to-share links. In this article, we'll guide you through the process of creating your own URL shortener using Flask, a lightweight web framework in Python. By the end, you'll have a functional URL shortener that can generate short links for long URLs and redirect users to the original destination.

Prerequisites: Before proceeding, ensure you have Python and Flask installed on your system. You can install Flask using pip:

Creating a URL shortener using Flask, SQLAlchemy, SQLite, and Jinja templates involves building a web application that allows users to input long URLs and generate short, shareable links. Below is a step-by-step guide to implementing this using Python and the mentioned technologies:

  1. Set up the project structure:

Create a new directory for your project and navigate to it in the terminal. Inside the project directory, create the following files and folders:

  • app.py: The main Flask application file.

  • templates/: A folder to store Jinja templates.

  • static/: A folder to store static files (CSS, JavaScript, etc. if needed).

  1. Set up the virtual environment:

Create a virtual environment and activate it:

bashCopy codepython3 -m venv env
source env/bin/activate  # for Mac/Linux
env\Scripts\activate  # for Windows
  1. Install Flask and SQLAlchemy:
  1.   Copy codepip install flask sqlalchemy
    
    1. Create the Flask application:

In app.py, import the required modules and create a Flask application. Initialize the Flask app and configure the database: Create a file named app.py and initialize the Flask app and database setup:

    pythonCopy codefrom flask import Flask, render_template, request, redirect
    from flask_sqlalchemy import SQLAlchemy

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

    # Create a URL model
    class URL(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        original_url = db.Column(db.String(200))
        short_code = db.Column(db.String(10))

        def __init__(self, original_url, short_code):
            self.original_url = original_url
            self.short_code = short_code

    # Define routes
    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            original_url = request.form['original_url']
            short_code = generate_short_code()  # Implement this function
            url = URL(original_url=original_url, short_code=short_code)
            db.session.add(url)
            db.session.commit()
            return redirect('/')
        else:
            urls = URL.query.all()
            return render_template('index.html', urls=urls)

    @app.route('/<short_code>')
    def redirect_to_url(short_code):
        url = URL.query.filter_by(short_code=short_code).first()
        if url:
            return redirect(url.original_url)
        else:
            return 'URL not found'

    # Run the application
    if __name__ == '__main__':
        db.create_all()
        app.run(debug=True)
  1. Create the Jinja template

Creating the Home Page Next (index.html), we'll set up the home page, where users can enter the long URL they want to shorten and can also be implemented in the database. Add the following route and function to your app.py:

htmlCopy code<!-- templates/index.html -->

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form action="/" method="post">
        <input type="text" name="long_url" placeholder="Enter long URL" required>
        <button type="submit">Shorten</button>
    </form>

    <h2>All Short URLs</h2>
    <ul>
        {% for url in all_urls %}
        <li><a href="{{ url.short_code }}">{{ url.short_code }}</a> - {{ url.long_url }}</li>
        {% endfor %}
    </ul>
</body>
</html>
  1. Run the application:

In the terminal, run the following command to start the Flask development server:

python app.py // flask run

Now you should have a URL shortener web app running on http://127.0.0.1:5000/. Users can input long URLs, and the app will generate short codes for them, which can be used to access the original URLs.Make sure to update the database URI in app. config['SQLALCHEMY_DATABASE_URI'] to reflect your desired location and filename for the SQLite database.

Remember, this is a basic implementation, and you can expand it further by adding features like analytics, custom URLs, and persistence using a database. Flask provides a flexible foundation for building more advanced applications.

Now you can share your shortened URLs and make your links more manageable and user-friendly.

Happy coding!