Introduction

A URL shortener is a useful tool for transforming long, complex URLs into shorter, more manageable links. In this guide, we'll create a basic URL shortener web application using Flask, a Python web framework. You'll learn how to take long URLs, generate short links, and redirect users to the original URLs. By following this guide, you'll be able to build a simple URL shortener with Flask for your projects or websites.


Step 1: Setting Up Your Flask Application

Begin by setting up your Flask application and creating a directory structure. Here's a sample structure:

url-shortener/
app.py
templates/
index.html

Step 2: Installing Flask

Install Flask, the Python web framework, using pip:

pip install Flask

Step 3: Creating the Flask Application

Create your Flask application. Here's an example of Python code:

# app.py
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)

Step 4: Creating the URL Shortening Logic

Create the URL shortening logic in your Flask application. Here's an example of Python code:

# app.py (continued)
import string
import random
# Dictionary to store shortened URLs
shortened_urls = {}
def generate_short_url():
characters = string.ascii_letters + string.digits
short_url = ''.join(random.choice(characters) for _ in range(6))
return short_url
@app.route('/shorten', methods=['POST'])
def shorten_url():
long_url = request.form['long_url']
short_url = generate_short_url()
shortened_urls[short_url] = long_url
return f'Short URL: <a href="/{short_url}">/{short_url}</a>'
@app.route('/<short_url>')
def redirect_to_long_url(short_url):
if short_url in shortened_urls:
return redirect(shortened_urls[short_url])
else:
return 'URL not found.'
if __name__ == '__main__':
app.run(debug=True)

Step 5: Creating HTML Templates

Create an HTML template for the index page where users can input long URLs. Here's an example:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
<h1>URL Shortener</h1>
<form method="POST" action="/shorten">
<label for="long_url">Enter a long URL:</label>
<input type="url" name="long_url" required>
<button type="submit">Shorten URL</button>
</form>
</body>
</html>

Conclusion

Building a basic URL shortener with Flask is a practical way to create shorter, more manageable links for your projects or websites. By following this guide, you've learned how to set up a Flask application, generate short URLs, and redirect users to the original long URLs. You can further enhance this application with additional features and customization to meet your needs.