使用Python进行HTTP基本认证
我希望我的用户能够访问我网站上的一个受保护的目录。这个目录里已经创建了 .htaccess 和 .htpasswd 文件。
用来请求用户名和密码的 HTML 代码是:
<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">
处理这个请求的 Python CGI 脚本是:
#!/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
当我输入正确的用户名和密码后,得到的“网页”是:
>
我怀疑我的 Python 代码中的 "print result" 可能有问题。我该怎么修复这个呢?
2 个回答
1
当你写:
resource = urllib2.urlopen(url)
# Here resource is your handle to the url
# resource provides a read function that mimics file read.
所以,resource.read()
# 就像读取文件一样读取这个网址。
print resource
# 打印的是资源对象的表示形式,而不是实际的内容。
1
从urlopen
调用返回的对象就像一个打开的文件流,你需要用read
方法来读取它的内容。
把print result
改成print result.read()
:
result = urllib2.urlopen(request)
print "Content-type: text/html\n\n"
print result.read()
或者,把result = urllib2.urlopen(request)
改成result = urllib2.urlopen(request).read()
:
result = urllib2.urlopen(request).read()
print "Content-type: text/html\n\n"
print result
可以看看这些例子: http://docs.python.org/library/urllib2.html#examples
lunchbox