我希望我的用户访问我的域上的受保护目录。
.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代码“打印结果”不正确。我怎样才能解决这个问题?
从 a 返回的对象urlopen
调用很像一个打开的文件流,你需要read
它来获取输出。
Change print result
to print result.read()
:
result = urllib2.urlopen(request)
print "Content-type: text/html\n\n"
print result.read()
或者,改变result = urllib2.urlopen(request)
to 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 http://docs.python.org/library/urllib2.html#examples
lunchbox
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)