[Baypiggies] urllib2, basic HTTP authentication, and tr.im

Daryl Spitzer daryl.spitzer at gmail.com
Tue Mar 10 16:26:26 CET 2009

I'm playing around, trying to write some code to use the http://tr.im
APIs (http://tr.im/api/) to shorten a URL.

After reading http://docs.python.org/library/urllib2.html, I tried:

    TRIM_API_URL = 'http://api.tr.im/api'
    auth_handler = urllib2.HTTPBasicAuthHandler()
    opener = urllib2.build_opener(auth_handler)
    response = urllib2.urlopen('%s/trim_simple?url=%s'
                               % (TRIM_API_URL, url_to_trim))
    url = response.read().strip()

response.code is 200 (I think it should be 202).  url is valid, but
the basic HTTP authentication doesn't seem to have worked, because the
shortened URL isn't in my list of URLs (at http://tr.im/?page=1).

After reading http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly
I also tried:

    TRIM_API_URL = 'api.tr.im/api'
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    opener = urllib2.build_opener(auth_handler)
    response = urllib2.urlopen('http://%s/trim_simple?url=%s'
                               % (TRIM_API_URL, url_to_trim))
    url = response.read().strip()

But I get the same results.  (response.code is 200 and url is valid,
but not recorded in my account at http://tr.im/.)

If I use query string parameters instead of basic HTTP authentication,
like this:

    TRIM_API_URL = 'http://api.tr.im/api'
    response = urllib2.urlopen('%s/trim_simple?url=%s&username=%s&password=%s'
                               % (TRIM_API_URL,
    url = response.read().strip()

...then not only is url valid but it's recorded in my tr.im account.
(Though response.code is still 200.)

Either there must be something wrong in my authentication code, or in
tr.im's.  (I've written api at tr.im to see if it's a known problem and
haven't received a response.)

Can anyone spot any problems?


More information about the Baypiggies mailing list