2011-11-30 3 views
5

내 사용자가 내 도메인의 보호 된 디렉토리로 이동하기를 원합니다. .htaccess와 .htpasswd가 모두 만들어지고 보호 된 라이브러리에 상주합니다.파이썬을 사용하는 HTTP 기본 인증

사용자 이름/암호 조합을 묻는 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"> 

파이썬 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 

나는 올바른 사용자 이름/암호 조합을 입력

, '웹 페이지'는 다음과 같습니다.

> 

파이썬 코드 "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의 제안과 동일합니다. –