How to Create a Simple URL Shortener Tool Using Python
How to Create a Simple URL Shortener Tool Using Python – In this tutorial, we will create a simple URL shortener tool using Python and Flask, a lightweight web framework.
This tool will allow users to input a long URL and receive a shorter, more manageable URL in return.
A Step-by-step Tutorial to Create a URL Shortener Tool Using Python
We’ll cover everything from setting up your environment to writing and running the code. By the end of this tutorial, you’ll have a functional URL shortener tool.
Prerequisites
Hide- Python installed on your system (Python 3.6+ is recommended).
- Flask installed. You can install Flask using pip.
Step 1: Setting Up Your Environment
First, create a virtual environment and install Flask. Let’s go through the step-by-step guide:
Creating a Virtual Environment
Open your terminal and run the following commands:
# Create a virtual environment
python -m venv url_shortener_env
# Activate the virtual environment
# On Windows
url_shortener_env\Scripts\activate
# On macOS/Linux
source url_shortener_env/bin/activate
Installing Flask
Install Flask using pip:
pip install Flask
Step 2: Writing the Code
Now, let’s write the code to create our URL shortener tool.
Importing Required Libraries
Create a Python file, e.g., app.py
, and add the following import statements:
from flask import Flask, request, redirect, url_for, render_template_string
import string
import random
Setting Up Flask App and Database
We’ll use a simple in-memory dictionary to store the URL mappings. For a more robust solution, you might use a database like SQLite or PostgreSQL.
app = Flask(__name__)
url_mapping = {}
Function to Generate Short URLs
We’ll create a function that generates a short URL key.
def zerobytecode_generate_short_url():
characters = string.ascii_letters + string.digits
short_url = ''.join(random.choice(characters) for _ in range(6))
return short_url
Route to Handle URL Shortening
This route will take a long URL from the user and return a shortened version.
@app.route('/shorten', methods=['POST'])
def zerobytecode_shorten_url():
original_url = request.form['url']
short_url = zerobytecode_generate_short_url()
url_mapping[short_url] = original_url
return f'Shortened URL: {request.host_url}{short_url}'
Route to Redirect Short URLs
This route will redirect users from the short URL to the original long URL.
@app.route('/<short_url>')
def zerobytecode_redirect_url(short_url):
original_url = url_mapping.get(short_url)
if original_url:
return redirect(original_url)
else:
return 'URL not found', 404
Main Function to Run the App
Finally, we’ll write the main function to run the Flask app.
if __name__ == "__main__":
app.run(debug=True)
Step 3: Running the Tool
Save your app.py
file and run it from the terminal:
python app.py
The Flask development server will start, and you can access the URL shortener tool by navigating to http://127.0.0.1:5000
in your web browser.
Step 4: Testing the Tool
To shorten a URL, you can use a simple HTML form. Here’s a basic HTML template for testing:
@app.route('/')
def home():
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
</head>
<body>
<h1>URL Shortener</h1>
<form action="/shorten" method="post">
<label for="url">Enter URL to shorten:</label>
<input type="text" id="url" name="url">
<input type="submit" value="Shorten">
</form>
</body>
</html>
''')
Add this route to your app.py
file and restart the server. You can now enter a URL in the form, and it will generate a shortened URL.
Wrapping Up: Creating Your First URL Shortener Tool Using Python
By following these steps, you can create a simple URL shortener tool using Python and Flask.
This tool can be further enhanced with additional features such as user authentication, analytics, and a database for storing URL mappings persistently.
This setup serves as a solid foundation for more advanced development and customization.