HTTP基本身份验证,使用Python。

5
我希望我的用户能够访问我域名下的受保护目录。 已经创建了.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
一个从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


1

当你写下:

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

所以,resource.read() # 读取 URL 就像读取文件一样。

print resource # 打印资源对象的 repr 而不是实际内容。


关于它如何打印对象的 repr,这是一个很好的补充。 - chown
谢谢,您的建议与@chown的建议相同。 - Paul van Toesmeer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接