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
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
<h1>URL Shortener</h1>
<form action="{{ url_for('shorten_url') }}" method="POST">
<label for="url">Enter your URL:</label>
<input type="url" id="url" name="url" required>
<button type="submit">Shorten</button>
</form>
{% if urls %}
<h2>Shortened URLs:</h2>
<ul>
{% for url in urls %}
<li><a href="{{ url.short_url }}">{{ url.short_url }}</a> - {{ url.original_url }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
Creating Flask Routes for the Web Interface
You will define a route for the homepage that renders the index.html template and passes a list of the ten most recently created URLs to the template as the URLs variable. It also defines an error handler for 404 errors that render the 404.html template.
@app.route('/')
def index():
# Render the homepage template
urls = Url.query.order_by(Url.created.desc()).limit(10).all()
return render_template('index.html', urls=urls)
@app.errorhandler(404)
def page_not_found(error):
# Render the 404 error template
return render_template('404.html'), 404
Implementing the URL Shortening Form
To implement the URL shortening form, you'll need to define a Flask route that handles the form submission and generates a short URL for the entered URL. Here's an example of how to do this:
@app.route('/shorten', methods=['POST'])
def shorten_url():
# Get the URL from the form submission
original_url = request.form['url']
# Generate a short URL for the original URL
short_url = generate_short_url(original_url)
# Store the original and short URLs in the database
url = Url(original_url=original_url, short_url=short_url)
db.session.add(url)
db.session.commit()
# Redirect to the homepage with the new URL added to the list
return redirect(url_for('index'))
This code defines a route for the /shorten URL that handles POST requests from the URL shortening form. It retrieves the original URL from the form submission using the request.form['url'], generates a short URL using the generate_short_url function from earlier and stores both URLs in the database using SQLAlchemy. Finally, it redirects the user to the homepage with the new URL added to the list.
Displaying the List of Shortened URLs
The code below retrieves the ten most recently created URLs from the database using an SQLAlchemy query and passes them to the index.html template as the URLs variable. The template uses the URL variable to display the shortened URL list.
With these changes, you should now have a fully functional URL shortener with a web interface built using Flask and Python!
@app.route('/')
def index():
# Retrieve the 10 most recently created URLs from the database
urls = Url.query.order_by(Url.created.desc()).limit(10).all()
# Render the homepage template with the list of URLs
return render_template('index.html', urls=urls)
Deploying the Application
Choosing a Hosting Platform
To deploy your Flask application, you must choose a hosting platform that supports Python applications. There are many hosting options available, but some popular choices for Flask applications include the following:
- Heroku
- Google App Engine
- AWS Elastic Beanstalk
- DigitalOcean
- PythonAnywhere
Each platform has strengths and weaknesses, so it's essential to research and choose the one that best fits your needs.
Final Thoughts
Building a URL shortener with Flask and Python is a great way to learn how to use Flask to build web applications. You can make more complex and advanced applications with the skills you've learned in this tutorial. Flask is a powerful and flexible framework that allows you to build applications quickly and easily, and it's an excellent choice for building web applications of any size and complexity. Access the code in the GitHub repo.
Opinions expressed by DZone contributors are their own.
Comments