Python Network Programming HTTP Client

Python Network Programming HTTP Client

In the HTTP protocol, a request from a client reaches a server and retrieves some data and metadata, assuming it’s a valid request. We can use various functions in the requests module to analyze the response from the server. The following Python program, run on the client, displays the response sent by the server.

Getting the Initial Response

In the following program, the get method of the requests module retrieves data from the server and prints it out in plain text.

import requests
r = requests.get('https://httpbin.org/')
print(r.text)[:200]

When we run the above program, we get the following output −

<!DOCTYPE html >
html lang="en">
<head>
  <meta charset="UTF-8">
  <title>httpbin.org</title>
  <link
href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+

Getting the Response from a Session Object

A session object allows you to save certain parameters across requests. It also persists cookies across all requests made from the Session instance. If you make multiple requests to the same host, the underlying TCP connection will be reused.

import requests
s = requests.Session()

s.get('http://httpbin.org/cookies/set/sessioncookie/31251425')
r = s.get('http://httpbin.org/cookies')

print(r.text)

When we run the above program, we get the following output −

{"cookies":{"sessioncookie":"31251425"}}

Handling Errors

If an error occurs due to problems with the server processing the request, the Python program can gracefully handle this exception using the timeout parameter, as shown below. The program will wait for the defined timeout value and then raise a timeout error.

requests.get('http://github.com', timeout=10.001)

Leave a Reply

Your email address will not be published. Required fields are marked *