Introduction

Creating a URL shortener is a useful web application that can help users convert long URLs into short, easy-to-share links. In this guide, we'll walk you through the process of building a URL shortener with Flask, a Python web framework. You'll learn how to set up your Flask application, create routes for shortening and redirecting URLs, and generate unique short codes for each URL.


Step 1: Setting Up Your Flask Application

Before you can build a URL shortener, make sure you have a Flask application. If not, you can create a basic Flask app like this:

from flask import Flask, render_template, request, redirect
app = Flask(__name)

Step 2: Creating Routes

Create routes to handle shortening and redirecting URLs. Here's an example of a route for shortening URLs:

url_map = {}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/shorten', methods=['POST'])
def shorten_url():
long_url = request.form['long_url']
short_code = generate_short_code()
url_map[short_code] = long_url
return render_template('shortened.html', short_url=f'/{short_code}')
@app.route('/<short_code>')
def redirect_to_url(short_code):
long_url = url_map.get(short_code)
if long_url:
return redirect(long_url)
return 'URL not found.'

Step 3: Generating Short Codes

Create a function to generate unique short codes for URLs. You can customize the logic for generating short codes according to your preferences.

import random
import string
def generate_short_code():
characters = string.ascii_letters + string.digits
short_code = ''.join(random.choice(characters) for _ in range(6))
return short_code

Step 4: Creating HTML Templates

Create HTML templates for rendering the URL shortener. Here's an example of an "index.html" template:

<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
<h1>URL Shortener</h1>
<form method="POST" action="/shorten">
<label for="long_url">Long URL:</label>
<input type="url" id="long_url" name="long_url" required>
<input type="submit" value="Shorten URL">
</form>
</body>
</html>

Additionally, create a "shortened.html" template for displaying the shortened URL.


Step 5: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

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

Now, you can run your application with the command python your_app.py and access your URL shortener.


Conclusion

Building a URL shortener with Flask is a practical project that demonstrates the capabilities of web development with Python. You've learned how to set up your application, create routes for shortening and redirecting URLs, and generate unique short codes. This project can be extended by adding features like custom short codes, analytics, and user accounts.