Backend Development 7 min read

Building a Short URL Service with Flask and Django

This article explains the benefits of using short‑link services for marketing, sharing, and SMS optimization, and provides step‑by‑step Flask and Django tutorials—including installation commands, MySQL integration, URL generation, routing, and database models—to create a functional short URL platform.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Building a Short URL Service with Flask and Django

Why use short‑link services? They improve online marketing effectiveness by enabling precise tracking of campaigns, facilitate easy sharing on social media, email, or blogs, and optimize SMS content by reducing character count while increasing click‑through rates.

Flask example

Install the required packages:

pip install flask flask-sqlalchemy flask-mysqldb

Flask application code:

from flask import Flask, request, redirect, url_for
import hashlib
import mysql.connector

app = Flask(__name__)

# MySQL configuration
config = {
    'user': 'root',
    'password': 'password',
    'host': 'localhost',
    'database': 'shortlinks'
}
conn = mysql.connector.connect(**config)
cursor = conn.cursor()

# Generate short URL using MD5
def generate_short_url(long_url):
    if isinstance(long_url, str):
        long_url = long_url.encode('utf-8')
    hash_object = hashlib.md5(long_url)
    hex_dig = hash_object.hexdigest()
    short_url = hex_dig[:6]
    return short_url

@app.route('/generate', methods=['POST'])
def generate():
    long_url = request.form['long_url']
    short_url = generate_short_url(long_url)
    add_link(short_url, long_url)
    return {'short_url': short_url}

@app.route('/
')
def redirect_to_long_url(short_url):
    query = "SELECT long_url FROM links WHERE short_url = %s"
    cursor.execute(query, (short_url,))
    result = cursor.fetchone()
    if result:
        return redirect(result[0])
    else:
        return "Invalid short URL", 404

def add_link(short_url, long_url):
    query = "INSERT INTO links (short_url, long_url) VALUES (%s, %s)"
    cursor.execute(query, (short_url, long_url))
    conn.commit()
    print("Added short URL:", short_url)

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

Django example

Install Django and MySQL driver:

pip install django
pip install mysqlclient

Configure MySQL in settings.py :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_database_name',
        'USER': 'your_mysql_username',
        'PASSWORD': 'your_mysql_password',
        'HOST': 'your_mysql_host',
        'PORT': 'your_mysql_port',
    }
}

Create a ShortLink model in models.py :

from django.db import models

class ShortLink(models.Model):
    short_url = models.CharField(max_length=6)
    long_url = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.short_url

Add view logic in views.py :

from django.shortcuts import render, redirect, get_object_or_404
from .models import ShortLink
from django.utils import timezone
import random, string

def generate_short_url(long_url):
    letters = string.ascii_letters + string.digits
    return ''.join(random.choice(letters) for _ in range(6))

def save_to_db(short_url, long_url):
    ShortLink(short_url=short_url, long_url=long_url).save()

def get_short_link(short_url):
    return ShortLink.objects.get(short_url=short_url)

def index(request):
    if request.method == 'POST':
        long_url = request.POST.get('long_url')
        short_url = generate_short_url(long_url)
        save_to_db(short_url, long_url)
        return redirect('redirect', short_url=short_url)
    return render(request, 'index.html')

def redirect(request, short_url):
    link = get_object_or_404(ShortLink, short_url=short_url)
    if request.method == 'GET':
        if link.created_at.replace(tzinfo=timezone.utc) < timezone.now().replace(tzinfo=timezone.utc):
            return HttpResponse('Link Expired', status=410)
        return redirect(link.long_url)
    return HttpResponse('Invalid Request', status=400)

These examples demonstrate how to set up a short‑link service using either Flask or Django, covering environment setup, database configuration, URL generation, routing, and handling of redirects and errors.

backend developmentMySQLDjangoFlaskURL Shortening
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.