[Tutor] getting a webpage via python

Kent Johnson kent37 at tds.net
Tue Mar 8 19:42:40 CET 2005


Paul Tremblay wrote:
> This is giving me 401 error, authorization required. Here's what I have:
> 
> 
> auth_handler = urllib2.HTTPBasicAuthHandler()
> auth_handler.add_password('realm', '127.0.0.1', 'myname', 'password')
> opener = urllib2.build_opener(auth_handler)
> # ...and install it globally so it can be used with urlopen.
> urllib2.install_opener(opener)
> print urllib2.urlopen('http://nnn.nnn.n.n').read()
> 
> This is almost the literal code, except I changed my log in name and
> passowrd.
> 
> What am I supposed to put for realm? I checked the docs on line, and it
> doens't mention what realm is.

The realm name is part of the web server authentication configuration. If you browse to the web page 
in your browser it will show the realm in the auth dialog. For example my browser (Firefox) shows

Enter user name and password for "Curriculum Builder" at http://localhost

The realm name is "Curriculum Builder"

> Also, I assume I am supposed to use the loopback address when I set up
> the handler?

No, use your server name, in your example nnn.nn.n.n

> Also, I know I am going to have another question once I solve this one,
> and since it is directly related, I'll ask it now. How can I use a
> password system that is not hardcoded in my text? Should I just setup a
> password file? 

Yes, something like that. You will have to store the password in plaintext (or a reversible cipher) 
since that is what HTTPBasicAuthHandler needs.

Kent




More information about the Tutor mailing list