HTTP基本认证,使用python [英] HTTP basic authentication, using python
问题描述
我希望我的用户转到我域上的受保护目录。
.htaccess和.htpasswd都被创建并驻留在受保护的库中。
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.
要求用户名/密码组合的html是:
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">
python cgi脚本为:
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:
>
我怀疑我的python代码打印结果不正确。我该如何解决?
I suspect that my python code "print result" is not correct. How can I fix this?
推荐答案
从 urlopen
返回的对象调用很像打开文件流,您需要读取
以获取输出。
The returned object from a urlopen
call is much like an open file stream, you need to read
it to get the output.
更改打印结果
到打印结果.read()
:
result = urllib2.urlopen(request)
print "Content-type: text/html\n\n"
print result.read()
或者更改结果= 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
午餐盒
这篇关于HTTP基本认证,使用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!