2013-12-19 6 views
1

파이썬에서 간단한 애플리케이션을 작성하려고합니다. 파이썬은 POST HTTP 메소드를 사용하여 서버에 텍스트를 보내고 일부 텍스트를 포함하는 응답을받습니다.POST 요청 파이썬에서 응답 본문을 가져올 수 없습니다.

서버 :

from http.server import * 
class MyServer(BaseHTTPRequestHandler): 

    def do_POST(self): 
     self.send_response(200) 
     self.send_header("Content-type","text/plain") 
     self.end_headers() 
     print(self.rfile.read().decode("UTF-8")) 
     self.wfile.write(bytes("TEST RESPONSE", "UTF-8")) 

address = ("",8000) 
httpd = HTTPServer(address, MyServer) 
httpd.serve_forever() 

클라이언트 :

import http.client 
class client: 
    def __init__(self): 
     h = self.request("127.0.0.1:8000", "POST", "OH YEA") 
     resp = h.getresponse() 
     print(resp.status) 
     #data = resp.read() 


    def request(self, host, metoda, strona): 
     headers = { "Host" : host, "Accept": r"text/plain" } 
     h = http.client.HTTPConnection(host) 
     h.request(metoda,"",strona,headers) 
     return h 

a = client() 

아니라 라인 데이터 한 = resp.read은() 주석 유지 모든의 콘솔 몸에 좋은 (물론 서버 GET 요청 인쇄를 작동 응답을 보냅니다.)하지만 응답 본문 서버를 읽으려고하면 요청 본문이 인쇄되지 않고 응답 상태 200이 나더라도 응답 본문 (전체 응용 프로그램이 "끊어짐")을 읽을 수 없습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 그 서버의 behevior 추측은 끝나지 않은 응답 처리와 관련이 있지만 응답 본문을 가져올 수 없다는 것을 끝내지 못합니다.

답변

1

HTTP 응답에 Content-Length 헤더가 누락되었습니다. 응답이 완료되면 HTTP 클라이언트가 모르는, 그래서이 완전히 아직 작동하지 않습니다 :

def do_POST(self): 
    content = bytes("TEST RESPONSE", "UTF-8") 
    self.send_response(200) 
    self.send_header("Content-type","text/plain") 
    self.send_header("Content-Length", len(content)) 
    self.end_headers() 
    print(self.rfile.read().decode("UTF-8")) 
    self.wfile.write(content) 

더 기다리고 계속해서 : 서버가 같은 문제가 있습니다 : 그것은 단지에서 읽기에 계속 rfile. 컬을 사용하여

def do_POST(self): 
    content = bytes("TEST RESPONSE", "UTF-8") 
    self.send_response(200) 
    self.send_header("Content-type","text/plain") 
    self.send_header("Content-Length", len(content)) 
    self.end_headers() 
    print(self.rfile.read(int(self.headers['Content-Length'])).decode("UTF-8")) 
    self.wfile.write(content) 

이 잘 작동합니다 :

$ curl -X POST http://localhost:8000 -d 'testrequest' 
TEST RESPONSE 

Content-Length 헤더없이이 작업을 수행하는 방법이 있습니다,하지만 시작을 위해,이 충분해야한다.

편집 : 이것은 HTTP 클라이언트/서버를 쓰기에 좋은 운동이지만, 생산 사용을 위해, 당신은 클라이언트 측에 대한 requestsWSGI 또는 전체 웹 프레임 워크와 같은 더 높은 수준의 추상화를 고려하는 것이 좋습니다 서버 측 (요구 사항에 따라 Flask 또는 Django은 일반적으로 많이 사용됨).

+1

내 하나님 남자 내가 사랑하는거야 나중에 http://docs.python.org/2/library/httplib.html의 사촌 나는 Content-Length가 automaticaly라고 생각했다. 이제는 물론 작품 :) :) 정말 고마워요 :) Btw : 메리 크리스마스와 새해 복 많이 받으세요 !!! – user2184057

+0

감사합니다 :-) 나는 클라이언트에서'Content-Length'에 대해 잘못되었을 수도 있습니다. 수동으로 설정하지 않고 시도 했습니까? 난 그냥 설명서를 쳐다 보면서, 그것은 작동합니다 :-) Btw. [이것은 Python 3.x의 문서입니다] (http://docs.python.org/3/library/http.html), 2.x 버전을 읽고있었습니다. – sk1p

관련 문제