Python Glossary Русский

all Python 3http.clientterm

http.client.HTTPResponse

responses

The server response returned by getresponse(): status, headers and body. The body is read with read() and arrives as bytes.

Syntax

resp = conn.getresponse(); resp.status; resp.reason; resp.getheader(name); resp.read()

The body can be read only once: a second read() returns b''. It arrives as bytes, not str; decode it using the charset from Content-Type. Headers are looked up case-insensitively with getheader(), and a missing header gives None, not KeyError. Until the response is fully read, no new request can be sent on the same connection. Chunked encoding is decoded for you; creating an HTTPResponse by hand is rarely needed, except on top of your own socket.

Examples

import http.client
import socket
server, client = socket.socketpair()
server.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\n' b'Content-Length: 5\r\n\r\nhello')
server.close()
resp = http.client.HTTPResponse(client)
resp.begin()  # getresponse() делает это сам
print(resp.status, resp.reason)  # → 200 OK
print(resp.getheader('content-type'))  # → text/plain; charset=utf-8
print(resp.getheader('X-Missing'))  # → None
print(resp.read(), resp.read())  # → b'hello' b''
client.close()
import http.client
import socket
server, client = socket.socketpair()
server.sendall(b'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n' b'3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n')
server.close()
resp = http.client.HTTPResponse(client)
resp.begin()
print(resp.read().decode())  # → abcde — куски склеены автоматически
client.close()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy