【问题标题】:HTTP basic authentication, using pythonHTTP基本认证,使用python
【发布时间】:2012-01-09 22:09:55
【问题描述】:

我希望我的用户访问我域中的受保护目录。 .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 代码“打印结果”不正确。我该如何解决这个问题?

【问题讨论】:

    标签: python html forms cgi


    【解决方案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

    午餐盒

    【讨论】:

      【解决方案2】:

      当你写的时候:

      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 的建议一样。
      猜你喜欢
      • 1970-01-01
      • 2016-07-27
      • 2012-01-06
      • 1970-01-01
      • 2012-01-02
      • 2011-05-06
      • 1970-01-01
      • 2011-05-03
      • 2011-04-05
      相关资源
      最近更新 更多