2011-11-30 15 views
5

私のユーザーは自分のドメインの保護されたディレクトリに行きたいです。 .htaccessと.htpasswdの両方が作成され、保護されたライブラリに存在します。HTTP基本認証、Pythonを使用して

ユーザー名/パスワードの組み合わせを要求HTMLです:PythonのCGIスクリプトがある

<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"> 

#!/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"が正しくないと思われます。これをどうすれば解決できますか?

答えて

1

urlopen呼び出しから返されるオブジェクトは、開いているファイルストリームとよく似ています。出力を取得するには、readする必要があります。

変更print resultprint 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

+0

ありがとうございます、あなたの提案はうまくいきます! –

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を表示します。

+0

オブジェクトの 'repr'をどのように出力するかについての良い追加。 – chown

+0

ありがとう、あなたの提案は@chownの提案と同じです。 –

関連する問題