How to Create a Link Shortener Using Python-Flask With Source Code

Tech Orcus
By -
6 minute read
0
Python link shortenr using flask with source code

Welcome to another awesome guide on Python projects! Today, we’re going to create a simple link shortener using Flask, a popular Python web framework. This guide is super easy to follow, even if you're new to coding. Let's get started!

What is a Link Shortener?

A link shortener is a tool that converts a long URL into a shorter, manageable one. For example, https://techorcus.blogspot.com/some-very-long-url could become something like https://short.ly/abc123. It’s widely used for simplifying URLs and tracking link clicks.

Step 1: Prerequisites

  • Python installed on your computer (preferably version 3.x).
  • A basic understanding of Python and Flask.
  • Install Flask: Run pip install flask in your terminal or command prompt.

Step 2: Setting Up the Flask App

Let’s create a new file called app.py and write the following code:

from flask import Flask, render_template, request, redirect, url_for
import random
import string

# Initialize Flask app
app = Flask("Tech-Orcus Shortify")

# Store shortened URLs in a dictionary
shortened_urls = {}

# Function to generate random short codes
def generate_short_code():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=6))

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/shorten', methods=['POST'])
def shorten():
    original_url = request.form['original_url']
    short_code = generate_short_code()
    shortened_urls[short_code] = original_url
    return render_template('index.html', short_code=short_code)

@app.route('/')
def redirect_to_url(short_code):
    if short_code in shortened_urls:
        return redirect(shortened_urls[short_code])
    return "URL not found!", 404

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

Code Explanation

  • Flask: We imported Flask and its modules to create the web app.
  • shortened_urls: A dictionary to store original URLs and their corresponding short codes.
  • generate_short_code(): Generates a random 6-character code using letters and digits to ensure a unique short code.
  • Routes:
    • /: The homepage where users can enter their URL.
    • /shorten: Processes the form input and generates a short code for the given URL.
    • /<short_code>: Redirects users to the original URL based on the short code.

Step 3: Create the HTML Template

Now, create a folder named templates in the same directory as app.py. Inside it, create a file called index.html with the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Tech-Orcus Shortify</title>
    <!-- Bootstrap CDN -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container mt-5">
        <h1 class="text-center mb-4">Tech-Orcus Shortify</h1>
        <form method="POST" action="/shorten" class="mb-3">
            <div class="mb-3">
                <label for="original_url" class="form-label">Enter URL to Shorten</label>
                <input type="url" class="form-control" id="original_url" name="original_url" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">Shorten URL</button>
        </form>

        <!-- Display short code if available -->
        {% if short_code %}
            <div class="alert alert-success text-center" role="alert">
                Short URL: <a href="/{{ short_code }}" target="_blank">http://127.0.0.1:5000/{{ short_code }}</a>
            </div>
        {% endif %}
    </div>
</body>
</html>

Code Explanation

  • Bootstrap is used for styling to make the form look clean and responsive.
  • The form sends the entered URL to the /shorten route using a POST request.
  • When a short code is generated, it is displayed below the form as a clickable link.

Step 4: Running the App

Run the app by executing python app.py. Open your browser and go to http://127.0.0.1:5000/. You can now enter any URL, click the "Shorten URL" button, and get a short, functional link!
Check out this images and videos


Testing on Phone 📱

Enhancements

Here are some ideas to make this project even better:

  • Database Integration: Use a database like SQLite or MongoDB to store URLs instead of a dictionary, which is temporary.
  • Custom Short Codes: Allow users to create their own custom short codes.
  • Analytics: Track how many times a short URL has been clicked.
  • Expiration: Add an expiration time for short links.

Scope

This project demonstrates basic web development concepts like routing, forms, and data handling using Flask. It can be expanded into a fully functional tool with features like authentication, URL previews, and more. With additional skills in front-end and back-end development, you can turn this into a commercial-grade application.

Conclusion

And that’s it! You’ve built a simple yet powerful link shortener using Python and Flask. Keep exploring and adding new features to learn more. If you have questions or run into issues, feel free to comment below. Happy coding!

Post a Comment

0Comments

Post a Comment (0)
Today | 17, April 2025