Ir al contenido principal

Ralsina.Me — El sitio web de Roberto Alsina

Using TinyURL in python

Is­n't this neat?

import urllib

def makeTiny(url):

  url='http://tinyurl.com/api-create.php?'+urllib.urlencode({'url':url})
  return urllib.urlopen(url).read()

>>> makeTiny('http://www.kde.org')
'http://tinyurl.com/3cnthx'
derelm / 2007-04-24 21:20:

neat but not exactly correct. try opening the returned url in your browser and you see what i mean.

leave out the urlencode stuff and it'll work as intended.

cheers
derelm

Roberto Alsina / 2007-04-24 22:06:

Hmmm... without the urlencode stuff it works even worse:

http://tinyurl.com/://www.k...

And if you use just www.kde.org:

http://tinyurl.com/kde.org

So, there is obviously something wrong still.

derelm / 2007-05-03 11:58:

>>> import urllib
>>>
>>> API_URL = 'http://tinyurl.com/api-crea...
>>>
>>> #what i meant with my first comment
>>> #issues a GET
>>> def makeTiny1(url):
... return urllib.urlopen(API_URL + "?url=%s" % url).read()
...
>>> #issues a POST
>>> def makeTiny2(url):
... return urllib.urlopen(API_URL, urllib.urlencode({'url': url})).read()
...
>>> def expandTiny(url):
... return urllib.urlopen(url).url
...
>>> test_url = "http://www.kde.org"
>>> makeTiny1(test_url) == makeTiny2(test_url), expandTiny(makeTiny1(test_url))
(True, 'http://www.kde.org')


Contents © 2000-2024 Roberto Alsina