Medium Python Project: How to make your own link shortener with graphical interface?

Hello world 👋🏻 my name is Francisco, fcoterroba on the Internet and today I bring you again a post in which we are going to carry out another project in our favorite language, Python 🐍.

This project is somewhat more complex than those previously carried out on the website.
If you haven't seen them already, I recommend watching them before continuing with this one: How can we do a calculator in the terminal? and the project where we do a script for generate QR codes.
Also, before seeing this, I recommend you visit the post that I consider to be at the same level. A project in which, using Free and public APIs, we were able to get a coin exchange with a graphical interface.

Before starting, although later I will explain what it is, I will I recommend visiting a post that I uploaded more than a month ago, in which I explain many of the most used computer terms in our day to day. Since, in this post, you will see words that you probably do not sound a lot. 🤯 You can reed the post here.

I also want to remind you that a few months ago I uploaded a video to my YouTube channel, very interesting, focused on home automation. Specifically, we connect, configure and install a smart light bulb 💡 with which you can change its color, turn it off, turn it on and much more simply by using your mobile phone and/or voice assistants such as Google, Alexa, etc. 👇🏻

Now yes, let's start!

What is a URL Shortener?

A link shortener, according to Wikipedia, is:

A type of software service that allows you to use short URLs which redirect to the original URL. The origin of this type of service is to make the URL more manageable and easier to share and remember.
It is primarily used to shorten deep links, which by their nature are usually long.

In short, a link or URL shortener is a program or service in which they transform a link, usually a long one, into a short one. Mainly using third party services.

There are services that even pay you a payment per visit for using these services. The benefit is usually realized given the advertising integrated into it in exchange for waiting for a certain amount of time.

And this is what we are going to do today, we are going to make a Python program with a graphical interface or GUI in which the user will insert a link and the program will return the shortened URL.

Before start, for real,, I want show you a GIF, the same as you'll able to do in less than an hour.

FIRST STEP

We are going to use a Python library called PyShorteners available at PyPI with documentation in ReadTheDocs.

To install this library we will have to write pip install pyshorteners in our terminal. (It is usually not necessary to write it in administrator mode)

2️⃣ 2️⃣ SECOND STEP 2️⃣

We are going to do a simple and quick test of how the library works, writing a small script to shorten my web page and display it in the terminal.

You can check correct operation by doing it yourself!

The generated link is the following, check that you return to my page! https://tinyurl.com/y6to3jqd

The code (correctly commented) that I have used is the following:

import pyshorteners # Importamos el paquete necesario y que hemos instalado previamente

s = pyshorteners.Shortener() # Creamos el objeto del paquete pyshorteners

# Mostramos por pantalla, usando la propiedad tinyurl del objeto que acabamos de
# crear, para que nos genere un enlace acortado, usando el servicio de tinyurl
print(s.tinyurl.short('https://www.fcoterroba.com')) 

3️⃣ THIRD STEP 3️⃣

Now that we have minimally controlled the library with which we are going to carry out the project, we are going to create the graphical interface.

I thought about creating something like this:

You already know and see, I don't make a living with the front-end... 😂

Although now I am going to explain and show the code that I have used for the project, do not leave yet since we have a pending crossroads!

The code that I have used is the following:

#Importamos los paquetes necesarios para la interfaz gráfica y el acortador
import pyshorteners
from tkinter import *
from tkinter import ttk

#Creamos la ventana con título, tamaño y demás parámetros
ventana = Tk() 
ventana.minsize(400, 360)
ventana.title("Acortador de enlaces | fcoterroba.com")
ventana.resizable(0,0)

#Función para acortar y mostrar enlace (la llamaremos posteriormente)
def acortamiento():
    s = pyshorteners.Shortener()
    acortado = s.tinyurl.short(acortar_entry.get())
    resultado_label = Label(ventana, text=acortado)
    resultado_label.grid(row=8, column=0)
    resultado_label.config(
        fg="black",
        bg="#16a596",
        font=("Arial", 20),
        padx=210,
        pady=20
        )

#Diseño del título
home_label = Label(ventana, text="¡Acortador de enlaces!")
home_label.config(
        fg="white",
        bg="#898b8a",
        font=("Candara", 30),
        padx=210,
        pady=20
    )
home_label.grid(row=0, column=0)

#Diseño del label y el entry_text para mostrar el texto y el input.
acortar_label = Label(ventana, text="¿Qué quieres acortar?", bg="#16a596")
acortar_entry = Entry(ventana)
acortar_label.grid(row=1, column=0, padx=5, pady=5)
acortar_entry.grid(row=2, column=0, padx=5, pady=5)

#Botón para hacer funcionar el método
boton = Button(ventana, text="¡Acorta! ✂", command=prueba)
boton.grid(row=6, column=0)

#Configuración general y muestra de la ventana principal con su respectivo color
ventana.configure(bg='#16a596')
ventana.mainloop()

So far so good and anyone could say that it is over but no, if we want to be good Python developers, we must realize that the result_label at the end, in the function, does not allow the user to copy and paste said link, only view it. It's something that either I don't know how to do or I swear you can't select text from a label.

To remedy this, I can think of two ways to do it.

The first is to establish a button under said label that opens the user's default web browser with said shortened link.

To do this we simply have to import the library webbrowser and use the method open, writing between the parentheses, said link.

#Botón para abrir enlace en el navegador
    boton = Button(ventana, text="Abrir enlace", command=abrir_enlace)
    boton.grid(row=9, column=0)   
    
def abrir_enlace():
    webbrowser.open(s.tinyurl.short(acortar_entry.get()))

The second option is to allow the user to obtain said link on their clipboard with a button.

For this we have to install an external library, called pyperclip. The installation is carried out, as you can imagine, using pip install pyperclip

Once installed we will simply call the library including the method copy and passing the link in parentheses.

#Botón para copiar al portapapeles
    boton = Button(ventana, text="Copiar enlace", command=copiar_enlace)
    boton.grid(row=10, column=0)   
    
def copiar_enlace():
    pyperclip.copy(s.tinyurl.short(acortar_entry.get()))

If you have followed the post to the letter, you will have something like this:

You can see the full repo on my GitHub's profile.

The last thing I have left to remember is that the tinyurl method is there because it is the service that I personally use to shorten links but the library of pyshorteners It has more than 15 services.

Some require an API to work correctly, but I'll leave that up to you!

Remember read the docs! https://pyshorteners.readthedocs.io/en/latest/index.html

And that's all for today guys, I hope you liked this post as much as I liked doing it, programming the project and fighting with the GUI! After all, this is the beauty of programming, don't you think? 🤓

See you here very soon and you already know that you can follow me on TwitterFacebookInstagram and LinkedIn. 🤟🏻

Leave a Reply

Your email address will not be published. Required fields are marked *