How to Build a URL Shortener Web App With Flask Framework
With the rapid growth in technology, URLs are generated to create a unique form of each URL by the URLs generator's APIs.
Join the DZone community and get the full member experience.
Join For FreeWith the rapid growth in technology, URLs are generated to create a unique form of each URL by the URLs generator's APIs. People find it challenging to share long, comprehensive links with their friends or place them as a reference to their work. URL shorteners now reduce the lengths of each long URL to those short ones that can be understandable or mastered. In this article, we will learn how to build and run your link shortener on your machine for free using Flask framework and Python.
What Is a URL Shortener?
A URL shortener is a tool that takes a long, complex URL and generates a shortened, easier-to-recall version. The shortened URLs typically redirect to the original, longer URL when clicked. URL shorteners are commonly used for social media posts, email messages, and other situations where a long URL could be more convenient and easier to share.
Prerequisites
To move along with this tutorial, you should consider the following:
- Basic understanding of Python programming, HTML, and CSS.
- Python 3.6 or later
- Flask framework
- A database system, such as SQLite or PostgreSQL.
Installing Flask
To install Flask, use the pip package manager for Python. Open a command prompt or terminal and enter the command below.
pip install flask
Creating and running the Flask app.
To create a flask app, you will create a Python file app.py and import the flask class from the flask module as shown:
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run(debug=True)
To run the app or start the server, run the Python file in the command prompt or terminal as:
python app.py
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Restarting with stat
Debugger is active!
Debugger PIN: 123-456-789
Choosing a Database System
There are various database systems that Flask supports, including SQLite, MySQL, PostgreSQL, and more. For this tutorial, we will use SQLite because it is lightweight and does not require a separate server for installation.
Creating the Database Schema
To start creating a database schema, you need to define tables and columns to be used and store data. This tutorial will create a table named URL with the following columns; Id, original_url, and short_url. We will use an object-relational mapping tool like SQLAlchemy.
CREATE TABLE urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
original_url TEXT NOT NULL,
short_url TEXT NOT NULL
);
Connecting Flask to the Database
To configure and connect the Flask database, you must configure the URL and initialize a database object in your Flask application, as shown.
from flask import Flask
import sqlite3
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///urls.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #disable tracking modifications not needed in the tutorial
db = sqlite3.connect('urls.db')
Generating Short URLs
You can use a hash function to generate short URLs that convert the original URL into a unique and short string. One joint hash function used for URL shorteners is MD5, but you can also use other hash functions like SHA-256 or Base64 encoding. MD5 takes the original URL as input, hashes it, and takes the first seven characters as short URLs.
import hashlib
def generate_short_url(original_url):
# Hash the original URL using MD5
hash_object = hashlib.md5(original_url.encode())
hash_hex = hash_object.hexdigest()
# Take the first 7 characters of the hash as the short URL
short_url = hash_hex[:7]
return short_url
Storing Short URLs in the Database
After creating short URLs, you need to store them in a database scheme developed. The database will store both the short and original URLs. You will use INSERT INTO SQL command to insert new records into the database.
def insert_url(original_url, short_url):
# Insert a new record into the urls table
cursor = db.cursor()
cursor.execute(
'INSERT INTO urls (original_url, short_url) VALUES (?, ?)',
(original_url, short_url)
)
db.commit()
cursor.close()
Redirecting Short URLs to Their Original URLs
To redirect short URLs to their original URLs, you need to define a Flask route that handles the short URL as a parameter and looks up the original URL using the SQL SELECT statement in the database.
If the original URL is found, the code uses Flask's redirect function to redirect the user to the original URL. If the short URL is not found, the code raises a 404 error using Flask's abort function.
@app.route('/<short_url>')
def redirect_url(short_url):
# Look up the original URL in the database
cursor = db.cursor()
cursor.execute(
'SELECT original_url FROM urls WHERE short_url = ?',
(short_url,)
)
result = cursor.fetchone()
cursor.close()
if result:
# Redirect to the original URL
return redirect(result[0])
else:
# Handle error if the short URL is not found
abort(404)
Handling Errors
To handle errors, you can define custom error pages for common HTTP errors like 404 Not Found or 500 Internal Server Error. The page_not_found function renders a custom 404 error page using Flask's render_template function and returns a 404 HTTP status code. The internal_server_error function does the same.
@app.errorhandler(404)
def page_not_found(error):
# Render a custom 404 error page
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(error):
# Render a custom 500 error page
return render_template('500.html'), 500
Creating HTML Templates
Create a template that defines a simple HTML form for the user to enter a URL to shorten and displays a list of shortened URLs, if any exist. The {{ }} syntax is used to interpolate variables from your Flask application, and the {% %} syntax is used for control structures like loops and conditionals. Save the template as index.html
Shortened URLs:
-
{% for url in urls %}
- {{ url.short_url }} - {{ url.original_url }} {% endfor %}