2014-09-15 4 views
0

: 내가 브라우저에서 실행 http://www.w3schools.com/php/php_forms.asp나는 다음과 같은 예를 사용

, 내가 브라우저에서 결과를 참조 :

Welcome John 
Your email address is [email protected] 

내가 파이썬 POST를 실행하면 HTTP 요청 :

:

import httplib, urllib 
params = urllib.urlencode({'@name': 'John','@email': '[email protected]'}) 
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/html"} 
conn = httplib.HTTPConnection("10.0.0.201") 
conn.request("POST","/welcome.php",params, headers) 
response = conn.getresponse() 
print "Status" 
print response.status 
print "Reason" 
print response.reason 
print "Read" 
print response.read() 
conn.close() 

나는 다음을 참조

Status 
200 
Reason 
OK 
Read 
<html> 
<body> 

Welcome <br> 
Your email address is: 
</body> 
</html> 

질문 : 파이썬에서 POST 요청 데이터를받는 방법?

+1

'urllib2' 라이브러리가있을 때 수동으로'HTTPConnection'을 구동하는 아픈 루트가 왜 필요한가 또는 ['requests'] (http://docs.python-requests.org/en/latest/)를 설치할 수 있습니까? –

답변

2

잘못된 형식 이름 이 잘못된 HTTP 메서드를 사용하고 있습니다. 더 @ 문자는 시작에 없습니다 :

params = urllib.urlencode({'name': 'John','email': '[email protected]'}) 

다음 GET, 당신이 사용 를 가리 형태, 처리 방법으로하지 POST, 대신 URL에 이러한 매개 변수를 추가해야하므로 :

conn.request("GET", "/welcome.php?" + params, '', headers) 

수동으로 HTTPConnection()을 운전하려고하면 혼란 스럽습니다.

from urllib2 import urlopen 
from urllib import urlencode 

params = urlencode({'name': 'John','email': '[email protected]'}) 
response = urlopen('http://10.0.0.201/welcome.php?' + params) 
print response.read() 

또는 당신은 훨씬 쉽게 여전히 자신을 만들기 위해 requests library의 사용 (별도 설치)를 만들 수 있습니다 : 당신은 예를 들어 대신 urllib2.urlopen()을 사용할 수

import requests 

params = {'name': 'John','email': '[email protected]'} 
response = requests.get('http://10.0.0.201/welcome.php', params=params) 
print response.content 
0

는 그냥 "@"를 제거하고 그것을 작동 :

Status 
200 
Reason 
OK 
Read 
<html> 
<body> 

Welcome John<br> 
Your email address is: [email protected] 
</body> 
</html> 

는 마티 피에 터스 주셔서 감사합니다.

POST 메서드의 경우 인프라 테스트 용도로이 예제를 사용했습니다. 마지막으로 나는 mysql 데이터베이스를 채우고 파이썬 스크립트를 사용하여 PHP를 통해 데이터를 가져와야한다. 가장 좋은 방법은 무엇입니까? HTTPConnection()을 권장하지 않는 이유는 무엇입니까?