DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.