Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want my users to go to a protected directory on my domain. Both .htaccess and .htpasswd are created and reside in the protected library.

The html that asks for a username/password combination is:

<form method="post" enctype="multipart/form-data" action="bin/logintest.cgi">
Username: <input type="text" name="username" size="20" value="please enter.."><br>
Password: <input type="password" name="password" size="20"><BR>
<input name="submit" type="submit" value="login">

The python cgi script is:

#!/usr/bin/python

import urllib2
import base64
import cgi

form = cgi.FieldStorage()
username = form.getfirst("username")
password = form.getfirst("password")

request = urllib2.Request("http://www.mydomain.com/protecteddir/index.html")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)

print "Content-type: text/html\n\n"
print result

When I enter a correct username/password combination, the resulting 'webpage' is:

>

I suspect that my python code "print result" is not correct. How can I fix this?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

The returned object from a urlopen call is much like an open file stream, you need to read it to get the output.

Change print result to print result.read():

result = urllib2.urlopen(request)

print "Content-type: text/html\n\n"
print result.read()

Or, change result = urllib2.urlopen(request) to result = urllib2.urlopen(request).read():

result = urllib2.urlopen(request).read()

print "Content-type: text/html\n\n"
print result

Check out these examples: http://docs.python.org/library/urllib2.html#examples

lunchbox

share|improve this answer
    
Thank you, your suggestion works! –  Paul van Toesmeer Nov 30 '11 at 19:29

When you write :

resource = urllib2.urlopen(url)
# Here resource is your handle to the url
# resource provides a read function that mimics file read.

So, resource.read() # Reads the url like a file.

print resource # prints the repr for the resource object and not the actual content.

share|improve this answer
    
Good addition about how it prints the repr of the object. –  chown Nov 30 '11 at 17:27
    
Thank you, your suggestion is the same as @chown 's suggestion. –  Paul van Toesmeer Nov 30 '11 at 19:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.