How To Use longurl Python Package
Last weekend I did a 24 hour code challenge in python. By "did" I do not mean that I completed it, but I did try until the very last possible moment. And then I came back to it this week to see if, given a little more time, I could get it working.
One small part of the larger problem involved taking tiny urls like http://t.co/vpegjcGCGf and grabbing the expanded, readable version. My first time around I did this by using the requests module to send a get request to the actual site and then grab the url from the response.
The problem with this was it was super slow.
I found a python package for longurl which lengthens short urls (you have probably seen these on twitter, I had not since I only pretend to have a twitter account). But I couldn't find any documentation.
It turns out there is a nice way to find out about a python module:
From your terminal, enter 'python' to open the python shell. Then
import module_name
help(module_name)
This opens up the class and shows you all the methods with a nice description of what each one does. YAY!
For longurl, I saw that there was a class called LongURL and it had a method called expand which took surl as an argument (also qurl=None but we'll come back to that).
So in my file.py I wrote:
LongURL().expand("http://t.co/blahblahblah")
But I got an error telling me that LongURL was undefined. WHY??
So after making sure 'import longurl' was the right thing to type ('import LongURL' and 'import LongUrl' didn't work) and after banging my head and explaining what was going wrong to Sterling, I was struck by genius. Modeled after other ways I'd seen things imported in my recent exploits in python, I tried adding this line:
from longurl import LongURL
But I was getting one last error. Apparently I was sending 3 arguments instead of 2 to 'expandable' a method called (upon further inspection) in the expand method of the LongURL class. I tried instead just calling expandable on my LongURL object:
LongURL().expandable("http://t.co/blahblahblah")
but the link I got back looked something like this:
http%3A%2F%2Ft.co%2FyNwC4iv5pm
and was not valid. So I tried passing that in as the qurl, the mysterious optional second argument of the expand method:
my_url = LongURL()
q_url = my_url.expandable("http://t.co/blahblahblah")
my_url.expand("http://t.co/blahblahblah", q_url)
And that did it. In help(longurl) it does say that the default for qurl is None and it should calculate it for you in the expand method if you don't provide it, but for some reason I had to pass it in. Perhaps this is a bug, or something weird with my environment. Either way the above seems to work.
So that's a basic strategy for for using longurl and working with python packages that you have never used before.