12: Building a URL Shortener with Variable Rules in Python

Building a URL Shortener with Variable Rules in Python

Introduction:

In this blog post, we will discuss how to build a URL shortener with variable rules in Python. We will create a web application that allows users to specify custom URLs and associate them with either a redirect URL or a file. By using variable routes and JSON data storage, we can efficiently handle different combinations of URLs and provide the appropriate response to the users.

Code Example: Below is an example code snippet demonstrating how to implement the functionality described above using Flask, a popular web framework for Python.

				
					from flask import Flask, redirect
import json
import os

app = Flask(__name__)

# Load URLs from urls.json file
def load_urls():
    if os.path.exists('urls.json'):
        with open('urls.json') as urls_file:
            return json.load(urls_file)
    return {}

# Define a route with a variable rule
@app.route('/<string:code>')
def redirect_to_url(code):
    urls = load_urls()
    
    if code in urls:
        if 'url' in urls[code]:
            return redirect(urls[code]['url'])
        elif 'file' in urls[code]:
            # Code to display the file associated with the code
            return f"Displaying file: {urls[code]['file']}"
    
    return "URL not found"

if __name__ == '__main__':
    app.run()
				
			

Explanation:

  1. The load_urls function is responsible for loading the URLs and their associated data from the urls.json file.
  2. The /<string:code> route defines a variable rule where any string after the first slash in the URL is captured as code.
  3. Inside the route function redirect_to_url, we check if the provided code exists in the loaded URLs data.
  4. If the code matches a key in the URLs dictionary, we check if it is associated with a URL or a file. If it’s a URL, we redirect the user to that URL. If it’s a file, we display a message indicating the file.
  5. If the code does not match any URLs in the data, we return a message indicating that the URL was not found.

Conclusion:

In this blog post, we have explored how to create a URL shortener with variable rules in Python using Flask. By utilizing variable routes and JSON data storage, we have implemented a simple yet effective solution for handling custom URLs and their associated actions. This approach can be extended and enhanced further to suit more complex requirements in real-world applications.