Building a URL Shortener with Redis
Introduction
In this tutorial, we’ll build a simple URL shortener using Redis and Python. The short URL service will generate a random short code for each URL, store it in Redis, and allow users to retrieve the original URL using the short code. We’ll also implement an expiration time for each shortened URL, making it expire after a specified period.
Environment Setup
First, install the necessary dependencies, including Upstash Redis and python-dotenv
for environment variables:
Database Setup
Create a Redis database using the Upstash Console or Upstash CLI, and export the UPSTASH_REDIS_REST_URL
and UPSTASH_REST_TOKEN
to your environment:
You can also use python-dotenv
to load environment variables from a .env
file:
Application Setup
In this example, we will build a URL shortener where each short URL will be stored in Redis with an expiration time.
Create url_shortener.py
:
Running the Application
Simply run the Python script:
This script will shorten a long URL, store the mapping in Redis, and print the shortened URL. It will then attempt to retrieve the original URL using the short code.
Here is an example output:
To monitor your data in Redis, you can use the Upstash Console and check out the Data Browser tab.
How to Use the URL Shortener for Web Applications
-
Extract the short code from the shortened URL (e.g.,
0lSLFI
). -
Look up the original URL in Redis using that code.
-
Redirect the user to the original URL.
Code Breakdown
-
Random Short Code Generation: The
generate_short_code
function creates a random string of characters (letters and digits) that will serve as the short code for the URL. -
Storing in Redis: The
shorten_url
function takes the original URL and stores it in Redis using the randomly generated short code as the key. Theex
parameter sets an expiration time (in seconds) for how long the shortened URL will be valid. -
Retrieving the Original URL: The
get_original_url
function takes the short code and looks it up in Redis to retrieve the original URL. If the short code doesn’t exist (due to expiration or other reasons), it returnsNone
. -
Expiration Handling: If the short code has expired, Redis automatically removes the entry, and the script will print a message indicating that the URL has expired or cannot be found.
Was this page helpful?