Building a URL Shortener in Python

Building a URL Shortener in Python body { font-family: sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; } header { background-color: #333; color: #fff; padding: 20px; text-align: center; } h1 { margin-top: 0; } nav { background-color: #eee; padding: 10px; text-align: center; } a { color: #333; text-decoration: none; } a:hover { text-decoration: underline; } article { background-color: #fff; padding: 20px; margin: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } h2 { color: #333; } pre { background-color: #222; color: #fff; padding: 10px; border-radius: 5px; overflow-x: auto; } code { font-family: monospace; } .highlight { background-color: #fffacd; padding: 2px; border-radius: 3px; }

Building a URL Shortener in Python

Introduction | Setup | Implementation

Introduction

In this blog series, we'll explore the exciting world of URL shortening by building our own service using Python and the Flask framework. URL shorteners are essential tools for sharing links in a more compact and user-friendly way. They're widely used on social media platforms, in email signatures, and for tracking link clicks.

By the end of this project, you'll have a basic understanding of how URL shortening works, how to create web applications with Flask, and some valuable Python programming skills.

Setup

Before we dive into coding, let's get our development environment ready:

1. Install Python

If you haven't already, download and install Python from the official website: https://www.python.org/ Make sure to add Python to your system's PATH environment variable.

2. Install Flask

Flask is a lightweight web framework for Python. You can install it using pip:

pip install Flask

3. Create a New Project

Create a new directory for your project and navigate to it in your terminal.

mkdir url-shortener
cd url-shortener

4. Initialize a Virtual Environment (Recommended)

Virtual environments are great for managing project dependencies. Create one using:

python3 -m venv .venv

Activate the environment:

source .venv/bin/activate

5. Create a Flask App

Create a file named app.py in your project directory and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
  return 'Hello, World!'

if __name__ == '__main__':
  app.run(debug=True)

This code sets up a simple Flask app that responds with "Hello, World!" when you access the root path.

6. Run the App

Run the following command in your terminal to start the app:

flask run

You should see a message indicating that the app is running on a specific address and port. Access it in your web browser to view the "Hello, World!" message.

Implementation

Now that we have our basic Flask app set up, let's start implementing our URL shortening logic.

1. Generating Shortened URLs

We'll use a library called shortuuid to generate unique and short random strings to represent shortened URLs. Install it using:

pip install shortuuid

Here's an example of generating a short UUID:

from shortuuid import ShortUUID

short_id = ShortUUID().random(length=6)
print(short_id) 

This will print a random 6-character string, like "a3h4f7".

2. Storing URL Mappings

We need a way to store the mappings between original URLs and their shortened versions. For simplicity, we'll use a Python dictionary for now. Later, we'll explore more persistent options like databases.

Let's update our app.py file:

from flask import Flask, redirect, url_for
from shortuuid import ShortUUID

app = Flask(__name__)

url_mapping = {} 

@app.route('/', methods=['GET', 'POST'])
def index():
  if request.method == 'POST':
    original_url = request.form['url']
    short_id = ShortUUID().random(length=6)
    url_mapping[short_id] = original_url
    return f'Shortened URL: {url_for("shorten", short_id=short_id)}'
  return '''
    
      Enter URL:
      
      Shorten
    
  '''

@app.route('/')
def shorten(short_id):
  if short_id in url_mapping:
    return redirect(url_mapping[short_id])
  else:
    return 'Short URL not found'

if __name__ == '__main__':
  app.run(debug=True)

This code adds a simple form for users to enter URLs. When the form is submitted, it generates a short ID, stores the mapping in the url_mapping dictionary, and redirects the user to the shortened URL. The shorten route handles requests for shortened URLs and redirects to the original URL if the short ID is found.

Run the app and try shortening some URLs! You'll have a working URL shortener in no time.