2012-02-11 2 views
3

내 HTTP 서버를 테스트하기 위해 청크로 묶인 HTTP 본문을 보내려고합니다. 내가 HTTP 요청의 몸이 transferrd 청크, 하지만, HTTP 요청의 몸이 청크 전송되지 와이어 샤크와 네트워크 패키지를 캡처 기대http.client가 청크로 청크 인코딩 된 HTTP 본문을 보내도록 강제하는 방법은 무엇입니까?

import http.client 

body = 'Hello World!' * 80 

conn = http.client.HTTPConnection("some.domain.com") 
url = "/some_path?arg=true_arg" 

conn.request("POST", url, body, {"Transfer-Encoding":"chunked"}) 

resp = conn.getresponse() 
print(resp.status, resp.reason) 

: 그래서 나는이 파이썬 코드를 썼다.

파이썬에서 http.client lib로 청크 분할체를 전송하는 방법은 무엇입니까?

답변

7

그래, 알겠습니다.

먼저 내 청크 인코딩 기능을 작성하십시오.

그런 다음) (putheader(), endheaders()를 putrequest 사용하고 대신 요청()의() 보내

import http.client 

def chunk_data(data, chunk_size): 
    dl = len(data) 
    ret = "" 
    for i in range(dl // chunk_size): 
     ret += "%s\r\n" % (hex(chunk_size)[2:]) 
     ret += "%s\r\n\r\n" % (data[i * chunk_size : (i + 1) * chunk_size]) 

    if len(data) % chunk_size != 0: 
     ret += "%s\r\n" % (hex(len(data) % chunk_size)[2:]) 
     ret += "%s\r\n" % (data[-(len(data) % chunk_size):]) 

    ret += "0\r\n\r\n" 
    return ret 


conn = http.client.HTTPConnection(host) 
url = "/some_path" 
conn.putrequest('POST', url) 
conn.putheader('Transfer-Encoding', 'chunked') 
conn.endheaders() 
conn.send(chunk_data(body, size_per_chunk).encode('utf-8')) 

resp = conn.getresponse() 
print(resp.status, resp.reason) 
conn.close() 
+2

chunk_data (즉, ret + = "% s \ r \ n"에 대한 두 번째 줄에는 단 하나의 구분 기호 만 사용하는 것이 좋습니다. % (data [ i * chunk_size : (i + 1) * chunk_size])) –

1

내가 좋을 것 당신은 이미처럼 데이터의 크기를 알고있는 경우 answer을 지정하면 Content-Length을 설정하고 다시 한 번 조회 할 수 있습니다. 이는 어쨌든 conn.send 번의 단일 호출로 수행하는 작업과 동일합니다.

청크 분할 전송 인코딩은 데이터의 크기가 얼마나 큰지 모를 때 가장 유용합니다. 동적으로 생성 된 콘텐츠

import httplib 

def write_chunk(conn, data): 
    conn.send("%s\r\n" % hex(len(data))[2:]) 
    conn.send("%s\r\n" % data) 

def dynamically_generate_data(): 
    for i in range(80): 
     yield "hello world" 

conn = httplib.HTTPConnection("localhost") 
url = "/some_path" 
conn.putrequest('POST', url) 
conn.putheader('Transfer-Encoding', 'chunked') 
conn.endheaders() 

for new_chunk in dynamically_generate_data(): 
    write_chunk(conn, new_chunk) 
conn.send('0\r\n') 

resp = conn.getresponse() 
print(resp.status, resp.reason) 
conn.close() 
관련 문제