python - HTTP基本认证,使用python

标签 python html forms cgi

我希望我的用户转到我域中 protected 目录。 .htaccess 和 .htpasswd 都被创建并驻留在 protected 库中。

请求用户名/密码组合的 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 代码“打印结果”不正确。我该如何解决这个问题?

最佳答案

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

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

饭盒

关于python - HTTP基本认证,使用python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329919/

相关文章:

python - 在顶部导入 Python 函数或在代码中调用它们

html - Angular 8 mat-autocomplete 错误 - 'matAutocomplete',因为它不是 'input' 的已知属性

html - 指定 CSS3 列的宽度

css - 将父级扩展为 float 子级 div

python - 如何将 Pandas 系列转换为索引和值的元组

python - 在什么情况下调用父类的多个元类?

python - Django Rest Framework (DRF) 如何根据 query_params 设置分页类?

php - 我可以使用 AJAX 将表单数据/变量传递到 jQuery 脚本中的 php 吗?

ruby-on-rails - ActiveAdmin单表继承公共(public)属性表单重写

javascript - AngularJS - 错误正文请求 POST