python requests keep alive false

Python Requests keep_alive false

If you are working on a project that requires making a lot of HTTP requests in Python, you may have come across the need to turn off keep-alive. Keep-alive is a feature that allows multiple requests to be made over a single TCP connection, which can be useful for reducing the overhead of establishing new connections.

However, in some cases, turning off keep-alive can be useful as well. For example, if you are making a lot of requests to different servers, keeping the connection alive for too long can result in resource exhaustion on your machine.

Using Requests Library

The Requests library is a popular Python library for making HTTP requests. To turn off keep-alive using Requests, you can set the "keep_alive" parameter to False when creating a Session object:


      import requests

      session = requests.Session()
      session.keep_alive = False

      response = session.get('https://www.example.com')
    

In this example, we create a new Session object and set the "keep_alive" parameter to False. This will ensure that each request made using this Session object will establish a new TCP connection.

Using urllib3

The urllib3 library is another popular Python library for making HTTP requests. To turn off keep-alive using urllib3, you can set the "Connection" header to "close" when creating a PoolManager object:


      import urllib3

      http = urllib3.PoolManager(headers={'Connection': 'close'})

      response = http.request('GET', 'https://www.example.com')
    

In this example, we create a new PoolManager object and set the "Connection" header to "close". This will ensure that each request made using this PoolManager object will establish a new TCP connection.

Conclusion

Turning off keep-alive can be useful in certain situations, such as when making a lot of requests to different servers. By using the examples provided above, you can easily turn off keep-alive in either Requests or urllib3.