Python Programming: Building a URL Shortener with Flask

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. Step 1 - Installing Flask
  5. Step 2 - Creating the Flask App
  6. Step 3 - Setting Up the Database
  7. Step 4 - Creating the Routes
  8. Step 5 - Implementing URL Shortening
  9. Step 6 - Testing the Application
  10. Conclusion

Overview

In this tutorial, we will learn how to build a URL shortener using Flask, a web framework for Python. A URL shortener takes a long URL and generates a shorter URL that redirects to the original long URL. By the end of this tutorial, you will have a functional URL shortener website.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming. Familiarity with SQL and databases would also be helpful, but it is not required.

Setup

Before we begin, make sure you have Python and pip (Python package installer) installed on your machine. You can download them from the official Python website.

Additionally, we’ll be using Flask and a SQLite database for this project. You can install Flask by running the following command in your terminal: bash pip install flask

Step 1 - Installing Flask

Flask is a lightweight web framework that allows us to create web applications easily. We need to install Flask before we can get started with building our URL shortener.

To install Flask, open your terminal and run the following command: bash pip install flask

Step 2 - Creating the Flask App

To create our Flask app, we need to create a new Python file. Open a text editor of your choice and create a new file called app.py. In this file, we’ll import Flask and create an instance of the Flask class. ```python from flask import Flask

app = Flask(__name__)
``` This code imports the Flask class and creates an instance of it called `app`. We pass `__name__` as the argument which helps Flask determine the root path of our application.

Step 3 - Setting Up the Database

For our URL shortener, we need a way to store the original long URLs and their corresponding short URLs. We’ll use SQLite, a lightweight relational database, for this purpose.

First, let’s import the necessary modules in our app.py file: ```python import sqlite3

# Create a connection to the database
connection = sqlite3.connect('url_shortener.db')
``` The code above imports the `sqlite3` module and creates a connection to the database. We also specify the name of the database file as `url_shortener.db`.

Next, we need to create a table to store the URLs. Add the following code after the previous imports: python with connection: cursor = connection.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS urls ( id INTEGER PRIMARY KEY AUTOINCREMENT, long_url TEXT NOT NULL, short_url TEXT NOT NULL ) ''') This code creates a table called urls with three columns: id, long_url, and short_url. The id column is the primary key, and the other two columns store the long and short URLs, respectively.

Step 4 - Creating the Routes

Now that we have our Flask app and database set up, let’s create the routes for our URL shortener.

We’ll start by creating a route for the home page. Add the following code to your app.py file: python @app.route('/') def home(): return "Welcome to the URL Shortener!" This code creates a route for the root URL ('/'). When a user visits the root URL, they will see the message “Welcome to the URL Shortener!”.

Next, let’s create a route for generating the short URL. Add the following code to your app.py file: ```python from flask import request

@app.route('/shorten', methods=['POST'])
def shorten():
    long_url = request.form['url']
    # Code to generate a short URL
    # Code to save the URLs in the database
    # Return the short URL to the user
``` This code creates a route for the `/shorten` URL. We specify that this route only accepts POST requests.

Inside the shorten function, we retrieve the long URL from the request form data. We will write the code to generate a short URL and save the URLs in the database in the next step.

Step 5 - Implementing URL Shortening

Now comes the important part – generating the short URL. There are many algorithms you can use for this purpose, but for simplicity, we’ll use a base62 encoding scheme.

First, let’s import the necessary modules in our app.py file: python import string import random Next, add the following helper functions: ```python def generate_short_url(): char_set = string.ascii_letters + string.digits return ‘‘.join(random.choice(char_set) for _ in range(6))

def is_url_valid(url):
    # Check if the URL is a valid URL
    # You can use a library like validators to perform this check
    return True  # Replace with actual validation logic
``` The `generate_short_url` function generates a random 6-character string from a combination of uppercase letters, lowercase letters, and digits.

The is_url_valid function checks if a given URL is valid. You can use a library like validators to perform this check, or write your own validation logic.

Now, let’s modify the shorten function to generate the short URL and save the URLs in the database: ```python from flask import redirect, url_for

@app.route('/shorten', methods=['POST'])
def shorten():
    long_url = request.form['url']
    
    if not is_url_valid(long_url):
        return "Invalid URL"
    
    short_url = generate_short_url()
    
    with connection:
        cursor = connection.cursor()
        cursor.execute('INSERT INTO urls (long_url, short_url) VALUES (?, ?)', (long_url, short_url))
    
    return f"Short URL: {request.host_url}{short_url}"
``` In this code, we first check if the long URL is valid using the `is_url_valid` function. If it's not valid, we return the message "Invalid URL".

If the URL is valid, we generate a short URL using the generate_short_url function.

Next, we save the long URL and short URL in the database using an INSERT query.

Finally, we return the short URL to the user.

Step 6 - Testing the Application

To test the application, save your app.py file and run the following command in your terminal: bash python app.py You will see output similar to the following: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Now, open your web browser and visit http://127.0.0.1:5000. You should see the message “Welcome to the URL Shortener!”.

To test the URL shortening functionality, you can use a tool like cURL or Postman to send a POST request to http://127.0.0.1:5000/shorten with the url parameter containing a long URL.

For example, using cURL: bash curl -X POST -d "url=https://www.example.com" http://127.0.0.1:5000/shorten You should receive a response with the short URL.

Congratulations! You have successfully built a URL shortener with Flask. You can now deploy this application to a hosting provider to make it accessible to the public.

Conclusion

In this tutorial, we learned how to build a URL shortener using Flask. We covered the basics of Flask, setting up a SQLite database, creating routes, and implementing URL shortening. We also learned how to test the application and deploy it to a hosting provider.

URL shorteners are widely used in web development to create short, memorable links. By building your own URL shortener, you have gained valuable experience in web development and database management. Keep exploring Flask and experimenting with different features to enhance your web application even further.