Python3

Python script: URL Shortener Service (with SQLite database)


import sqlite3
import string
import random

# Connect to SQLite database
conn = sqlite3.connect('url_shortener.db')
c = conn.cursor()

# Create table to store URLs and short codes
c.execute('''CREATE TABLE IF NOT EXISTS urls
(id INTEGER PRIMARY KEY, original_url TEXT, short_code TEXT)''')

# Function to generate a random short code
def generate_short_code():
characters = string.ascii_letters + string.digits
short_code = ''.join(random.choices(characters, k=6))
return short_code

# Function to shorten a URL
def shorten_url(original_url):
short_code = generate_short_code()

# Check if short code already exists
while c.execute("SELECT id FROM urls WHERE short_code=?", (short_code,)).fetchone():
short_code = generate_short_code()

c.execute("INSERT INTO urls (original_url, short_code) VALUES (?, ?)", (original_url, short_code))
conn.commit()

return short_code

# Function to get original URL from short code
def get_original_url(short_code):
result = c.execute("SELECT original_url FROM urls WHERE short_code=?", (short_code,)).fetchone()

if result:
return result[0]
else:
return "URL not found for the given short code."

# Close database connection
def close_connection():
conn.close()

The above Python script demonstrates a simple URL shortener service using an SQLite database. The script defines functions to generate a random short code, shorten a URL by storing it in the database with a unique short code, and retrieve the original URL from a given short code.

The script starts by connecting to an SQLite database file named “url_shortener.db” and creating a table named “urls” to store the original URLs and their corresponding short codes. The `generate_short_code` function generates a random alphanumeric short code of length 6 characters.

The `shorten_url` function takes an original URL as input, generates a short code, checks if the short code already exists in the database, and inserts the original URL and short code into the “urls” table. The `get_original_url` function retrieves the original URL corresponding to a given short code from the database.

Finally, the script includes a `close_connection` function to close the database connection when done.

This script provides a basic implementation of a URL shortener service using SQLite as the database backend.