HTTP基本身份验证,使用python

Pau*_*eer 5 html python forms cgi

我希望我的用户转到我的域上的受保护目录..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">
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

当我输入正确的用户名/密码组合时,生成的"网页"是:

>
Run Code Online (Sandbox Code Playgroud)

我怀疑我的python代码"打印结果"不正确.我怎样才能解决这个问题?

cho*_*own 1

调用返回的对象urlopen很像一个打开的文件流,您需要read它来获取输出。

改成:print resultprint result.read()

result = urllib2.urlopen(request)

print "Content-type: text/html\n\n"
print result.read()
Run Code Online (Sandbox Code Playgroud)

或者,更改result = urllib2.urlopen(request)result = urllib2.urlopen(request).read()

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

print "Content-type: text/html\n\n"
print result
Run Code Online (Sandbox Code Playgroud)

查看这些示例:http://docs.python.org/library/urllib2.html#examples

饭盒