Wednesday, April 24, 2024
HomePythonMaking a url shortener in python

Making a url shortener in python


Hello there fellas. In the present day on this put up i’m going to indicate you the way we are able to use python to make bulk urls tiny. Let me clear that we don’t make a url shortening SERVICE as an alternative what we’re going to do is that we’re going to unofficially use the tinyurl api (Tinyurl is a url shortening service). There’s not any official python api launched by tinyurl. So lets start with this:

Do required imports

So initially now we have to do some imports. We have now to import 7 libraries to make this work.

from __future__ import with_statement
import contextlib
strive:
    from urllib.parse import urlencode
besides ImportError:
    from urllib import urlencode
strive:
    from urllib.request import urlopen
besides ImportError:
    from urllib2 import urlopen
import sys

We may have imported only one library to make this work however so as to make a great url shortener now we have to import these seven libraries.

Implement make_tiny mathod

So now now we have to start out making a way that may deal with the url shortening. Watch the code intently as a result of it’s self explanatory however nevertheless i’ll clarify it later.

def make_tiny(url):
    request_url = ('http://tinyurl.com/api-create.php?' + 
    urlencode({'url':url}))
    <a href="http://freepythontips.wordpress.com/2013/07/28/the-with-statement/">with</a> contextlib.closing(urlopen(request_url)) as response:
        return response.learn().decode('utf-8')

Did you handle to know the code? Let me clarify it to the novices. To begin with we outline a make_tiny operate which takes a url as an enter. After that we begin defining the working of our operate. The url_encode takes a url as an enter and encodes it i.e escapes it. After that we append the escaped url to the top of tinyurl’s api url. Then we open the request_url utilizing urlopen. And lastly we learn the response after changing it to utf-8. Why did we convert the response to utf-8? The rationale for that is that the urlopen operate returns a stream of bytes reasonably than a string so so as to print it and alter it now we have to transform it into utf-8. Was that troublesome?

So now the following step is to get the enter from the consumer. For this we’re going to use the sys library.

Outline the primary operate

So lets write the principle() operate for our little script. Right here’s the code for it:

def primary():
    for tinyurl in map(make_tiny, sys.argv[1:]):
	print(tinyurl)

So what are we doing right here? We’re getting the consumer enter by utilizing sys.argv. We have now not restricted ourself to just one url as an enter as an alternative we’re saying that give us as many urls as you need, we’ll crush them and make them tiny. What sys.argv[1:] does is that it leaves the primary two arguments (counting begins from 0) and takes all the remainder of the arguments and produces a listing of these arguments. For instance in the event you kind:

$ python script.py url1 url2 url3

sys.argv[1:] will go away python and script.py and can produce the next listing:

[url1,url2,url3]

Wait! what’s that map() operate over there? Most novices will really feel confused as most of them have by no means used map. map() is a straightforward approach of looping over a listing and passing it to a operate one after the other. The map() operate above there may be equal to:

def primary():
    urls = sys.argv[1:]
    for url in urls:
        tinyurl = make_tiny(url)
        print tinyurl

I hope the above code instance cleared away any confusions about map() operate.

Add ending touches

Now lets wrap up our code. The one factor left is that this:

if __name__ == '__main__':
    primary()

Add this to the top of your code. This tells us whether or not the script was executed independently from the shell or was it referred to as by one other script. That is fairly helpful if you wish to use this script later in every other undertaking.

Lastly:

So right here’s the entire script:

from __future__ import with_statement
import contextlib
strive:
	from urllib.parse import urlencode
besides ImportError:
	from urllib import urlencode
strive:
	from urllib.request import urlopen
besides ImportError:
	from urllib2 import urlopen
import sys

def make_tiny(url):
	request_url = ('http://tinyurl.com/api-create.php?' + 
	urlencode({'url':url}))
	with contextlib.closing(urlopen(request_url)) as response:
		return response.learn().decode('utf-8')

def primary():
	for tinyurl in map(make_tiny, sys.argv[1:]):
		print(tinyurl)

if __name__ == '__main__':
	primary()

Contemplating that you’ve got saved this script as url_shortener.py you need to run it like this from the shell:

$ python url_shortener.py url1 url2 url3

If you wish to save these tinyurls right into a txt file then concern this command:

$ python url_shortener.py url1 > urls.txt

I hope you preferred right now’s put up. This script can work on python 2 and python 3 each. It was primarily aimed toward two sort of viewers. Firstly those that are studying python and wish to discover ways to make a easy but helpful script and people who wish to discover ways to make a url shortener in python. Do share your view within the feedback bellow and keep tuned for the following put up. If you’d like common dose of python suggestions and tutorials delivered to the doorstep then take into account following my weblog.

You may also like:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments