Linux

How To Build URL Shortener using Python

Build URL Shortener using Python

In the digital age, sharing links is an integral part of communication and marketing strategies. However, long URLs can be cumbersome and unattractive. This is where URL shorteners come into play. They simplify lengthy web addresses into concise, manageable links that are easy to share across various platforms. In this article, we will guide you through the process of building your own URL shortener using Python, specifically leveraging the Flask framework and the pyshorteners library.

Understanding URL Shortening

What is URL Shortening?

URL shortening is the process of converting a long web address into a shorter, more user-friendly version. This technique is widely used in social media posts, email marketing campaigns, and anywhere else where space is limited or aesthetics matter. By using a URL shortener, you can make links more appealing and easier to remember.

How URL Shorteners Work

At its core, a URL shortener functions by mapping a long URL to a unique identifier that redirects users to the original link. When someone clicks on the shortened link, they are redirected to the original URL. This mechanism not only simplifies sharing but can also provide valuable insights through analytics, such as click tracking and geographic data of users.

Setting Up Your Environment

Prerequisites

Before diving into coding, ensure that you have a basic understanding of Python and its syntax. You should also have Python installed on your machine. If you haven’t installed Python yet, download it from the official website and follow the installation instructions for your operating system.

Creating a Virtual Environment

A virtual environment allows you to manage dependencies for your project without affecting system-wide packages. Follow these steps to create a virtual environment:

python3 -m venv url_shortener_env
source url_shortener_env/bin/activate  # On Windows use: url_shortener_env\Scripts\activate

Installing Required Libraries

Next, install Flask for web development and pyshorteners for shortening URLs. Use pip to install these libraries:

pip install Flask pyshorteners

Building the URL Shortener

Step 1: Create the Flask Application

Start by creating a new Python file named app.py. This will be the main application file where we define our routes and logic.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')
    
if __name__ == '__main__':
    app.run(debug=True)

This code initializes a Flask application and sets up a basic route for the homepage.

Step 2: Creating the HTML Form

Create an HTML file named index.html. This file will contain a simple form that allows users to input their long URLs.

<!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>
</head>
<body>
    <h1>URL Shortener</h1>
    <form method="POST" action="/shorten">
        <input type="text" name="url" placeholder="Enter your URL here" required>
        <button type="submit">Shorten</button>
    </form>
</body>
</html>

This form captures user input and submits it to the server for processing.

Step 3: Handling Form Submission

Add functionality in app.py to handle form submissions when users input their URLs:

import pyshorteners

@app.route('/shorten', methods=['POST'])
def shorten_url():
    long_url = request.form['url']
    shortener = pyshorteners.Shortener()
    short_url = shortener.tinyurl.short(long_url)
    return f'Shortened URL: {short_url}'

This code snippet uses the pyshorteners library to generate a shortened version of the provided long URL.

Step 4: Storing Shortened URLs

If you want to keep track of shortened URLs for future reference or analytics purposes, consider storing them in a database. For this example, we will use SQLite.

from flask_sqlalchemy import SQLAlchemy

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

class Url(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    original_url = db.Column(db.String(500), nullable=False)
    short_url = db.Column(db.String(100), unique=True, nullable=False)

db.create_all()

This code sets up an SQLite database with a table for storing original URLs along with their corresponding shortened versions.

Step 5: Displaying Shortened URLs

You can enhance user experience by displaying previously shortened URLs on your homepage. Modify your home() function as follows:

@app.route('/')
def home():
    urls = Url.query.all()
    return render_template('index.html', urls=urls)

This modification retrieves all stored URLs from the database and passes them to the HTML template for display.

Enhancing Functionality

Add Custom Short URLs

You can allow users to specify custom identifiers for their shortened URLs. Modify your HTML form to include an additional input field:

<input type="text" name="custom_id" placeholder="Custom ID (optional)">

Add logic in your shorten_url() function to handle custom IDs:

custom_id = request.form.get('custom_id')
if custom_id:
    # Check if custom ID already exists
    existing_url = Url.query.filter_by(short_url=custom_id).first()
    if existing_url:
        return 'Custom ID already taken! Please choose another.'
    else:
        new_url = Url(original_url=long_url, short_url=custom_id)
else:
    new_url = Url(original_url=long_url, short_url=short_url)

db.session.add(new_url)
db.session.commit()

Implementing Analytics Tracking

An essential feature of any URL shortener is tracking how many times each link has been clicked. You can implement this by adding an additional column in your database model:

click_count = db.Column(db.Integer, default=0)

You would then increment this count each time someone clicks on the shortened link:

@app.route('/<short_id>', methods=['GET'])
def redirect_short_url(short_id):
    url_entry = Url.query.filter_by(short_url=short_id).first_or_404()
    url_entry.click_count += 1
    db.session.commit()
    return redirect(url_entry.original_url)

Troubleshooting Tips

  • Error 404:If you encounter a 404 error when trying to access shortened URLs, ensure that your custom IDs are unique and correctly mapped in your database.
  • No Response from Server: If your application isn’t responding as expected, check if Flask is running in debug mode. This will provide detailed error messages in your console.
  • Database Issues: If you face issues with SQLite connections or migrations, ensure that your database URI is correctly set up and that you’ve run db.create_all().
  • Pip Installation Errors: If you encounter issues while installing packages via pip, ensure that you’re using an active virtual environment.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button