DEV Community

petercour
petercour

Posted on

1 4

Short URLS from Python

Many times you'll have long URLs that need to go to another device. Like say you have a long url in one computer, but you want to open that on another computer or phone.

To solve that problem, you can use short urls, or an url shortener.
But, did you know you can do that from Python?

#!/usr/bin/python3
import urllib.request

def tiny_url(url):
    apiurl = "http://tinyurl.com/api-create.php?url="
    tinyurl = urllib.request.urlopen(apiurl + url).read()
    return tinyurl.decode("utf-8")

print(tiny_url('https://news.ycombinator.com/item?id=20342791'))

This will output a short url for "https://news.ycombinator.com/item?id=20342791".

You can turn this in a little command line app

./tinyurl.py https://duckduckgo.com

Like this:

#!/usr/bin/python3                                                                                                        
import urllib.request
import sys

def tiny_url(url):
    apiurl = "http://tinyurl.com/api-create.php?url="
    tinyurl = urllib.request.urlopen(apiurl + url).read()
    return tinyurl.decode("utf-8")

url = sys.argv[1]
print(url)
print(tiny_url(url))

Learn Python?

Jetbrains image

Don’t Become a Data Breach Headline

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. Is your CI/CD protected? Check out these nine practical tips to keep your CI/CD secure—without adding friction.

Learn more

Latest comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay