[Tutor] password protection in httplib

Kent Johnson kent37 at tds.net
Thu Mar 2 14:02:46 CET 2006


Andre Engels wrote:
> Thanks for your help; it brought me quite a bit farther, but not as
> far as I wanted to come. The authentication is basic authentication,
> and I have been able to adapt the programs so that I now get my pages
> correctly.
> 
> However, the program uses not only 'GET' operations, but also 'PUT'
> operations. These are done using httplib rather than urllib, and I
> cannot see at this point how I can mimick those using urllib2.

The docs don't spell it out, but if you pass the 'data' parameter to 
urllib2.urlopen(), it will make a POST request instead of a GET. The 
data has to be formatted as application/x-www-form-urlencoded; 
urllib.urlencode() will do this for you.

So for example:

import urllib, urllib2
data = dict(param1='foo', param2='bar')
data = urllib.urlencode(data)

# set up your basic auth as before
result = urllib2.urlopen('http://some.server.com', data).read()

Kent



More information about the Tutor mailing list