In this blog series, we'll explore the exciting world of URL shortening by building our own service using Python and the Flask framework. URL shorteners are essential tools for sharing links in a more compact and user-friendly way. They're widely used on social media platforms, in email signatures, and for tracking link clicks.
By the end of this project, you'll have a basic understanding of how URL shortening works, how to create web applications with Flask, and some valuable Python programming skills.
Before we dive into coding, let's get our development environment ready:
If you haven't already, download and install Python from the official website: https://www.python.org/ Make sure to add Python to your system's PATH environment variable.
Flask is a lightweight web framework for Python. You can install it using pip:
pip install Flask
Create a new directory for your project and navigate to it in your terminal.
mkdir url-shortener
cd url-shortener
Virtual environments are great for managing project dependencies. Create one using:
python3 -m venv .venv
Activate the environment:
source .venv/bin/activate
Create a file named app.py
in your project directory and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
This code sets up a simple Flask app that responds with "Hello, World!" when you access the root path.
Run the following command in your terminal to start the app:
flask run
You should see a message indicating that the app is running on a specific address and port. Access it in your web browser to view the "Hello, World!" message.
Now that we have our basic Flask app set up, let's start implementing our URL shortening logic.
We'll use a library called shortuuid
to generate unique and short random strings to represent shortened URLs. Install it using:
pip install shortuuid
Here's an example of generating a short UUID:
from shortuuid import ShortUUID
short_id = ShortUUID().random(length=6)
print(short_id)
This will print a random 6-character string, like "a3h4f7".
We need a way to store the mappings between original URLs and their shortened versions. For simplicity, we'll use a Python dictionary for now. Later, we'll explore more persistent options like databases.
Let's update our app.py
file:
from flask import Flask, redirect, url_for
from shortuuid import ShortUUID
app = Flask(__name__)
url_mapping = {}
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
original_url = request.form['url']
short_id = ShortUUID().random(length=6)
url_mapping[short_id] = original_url
return f'Shortened URL: {url_for("shorten", short_id=short_id)}'
return '''
Enter URL:
Shorten
'''
@app.route('/')
def shorten(short_id):
if short_id in url_mapping:
return redirect(url_mapping[short_id])
else:
return 'Short URL not found'
if __name__ == '__main__':
app.run(debug=True)
This code adds a simple form for users to enter URLs. When the form is submitted, it generates a short ID, stores the mapping in the url_mapping
dictionary, and redirects the user to the shortened URL. The shorten
route handles requests for shortened URLs and redirects to the original URL if the short ID is found.
Run the app and try shortening some URLs! You'll have a working URL shortener in no time.