DEV Community

Cover image for Following redirects with http.client Python module
Talles L
Talles L

Posted on

Following redirects with http.client Python module

Unfortunately, there is no configuration for automatic following redirects (3XX status) while using http.client Python module.

If you are stubborn like me and still wants to use the module, here is a snippet for following redirects:

#! /usr/bin/python3

from http.client import HTTPSConnection
from urllib.parse import urljoin

def get(host, url):
    print(f'GET {url}')

    connection = HTTPSConnection(host)
    connection.request('GET', url)

    response = connection.getresponse()
    location_header = response.getheader('location')

    if location_header is None:
        return response
    else:
        location = urljoin(url, location_header)
        return get(host, location)

response = get('en.wikipedia.org', '/api/rest_v1/page/random/summary')

print(response.read())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)