Python Network Programming HTTP Response
Python Network Programming HTTP Response
HTTP, or the Hypertext Transfer Protocol, operates in a client-server model. Typically, a web browser is the client, and the computer hosting the website is the server. After receiving a request from the client, the server generates a response and sends it back to the client in a specific format.
After receiving and interpreting the request message, the server responds with an HTTP response message.
* A status line
* Zero or more header (general | response | entity) fields, followed by a CRLF
* A blank line (i.e., nothing before the CRLF), indicating the end of the header fields.
* An optional message body
The following sections explain each entity used in an HTTP response message.
Status-Line
The status line consists of the protocol version and a numeric status code, along with an associated textual phrase. These elements are separated by space characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
HTTP-Version
A server supporting HTTP 1.1 will return the following version information.
HTTP-Version = HTTP/1.1
Status-Code
The Status-Code element is a three-digit integer. The first digit of the Status-Code defines the response category, while the second two digits do not have any classification effect. The first digit has five possible values.
S.N. | Code and Description |
---|---|
1 | 1xx: Informational This means the request was received and processing is continuing. |
2 | 2xx: Success This means the action was successfully received, understood, and accepted. |
3 | 3xx: Redirect This means further action must be taken to complete the request. |
4 | 4xx: Client Error This means the request contained incorrect syntax or could not be fulfilled. |
5 | 5xx: Server Error This means the server failed to complete an apparently valid request. |
HTTP status codes are extensible; HTTP applications are not required to understand the meaning of all registered status codes.
Using Python Requests
In the following Python program, we use the urllib3 module to issue an HTTP GET request and receive a response containing data. It also provides response codes, which are also managed by functions within the module. The PoolManager object handles all the details of connection pooling, including thread safety.
import urllib3
http = urllib3.PoolManager()
resp = http.request('GET', 'http://tutorialspoint.com/robots.txt')
print resp.data
# get the status of the response
print resp.status
When we run the above program, we get the following output −
User-agent: *
Disallow: /tmp
Disallow: /logs
Disallow: /rate/*
Disallow: /cgi-bin/*
Disallow: /videotutorials/video_course_view.php?*
Disallow: /videotutorials/course_view.php?*
Disallow: /videos/*
Disallow: /*/*_question_bank/*
Disallow: //*/*/*/*/src/*
200