Search code examples
pythonurllib

How to use `allow_redirects` in Python 2.7 in order to solve "302 Found" status


Problem Description

I am using the following the following python code in order to retrieve data from a give website through an API. The problem is that I am not receiving anything. When I print(str(response.status)+" "+response.reason), I get the following: 302 FOUND and nothing is being printed. From what I saw The HTTP response status code 302 Found is a common way of performing URL redirection.

Question

I saw that there is a way to set allow_redirects to False in order to solve that problem. I am forced to use python 2.7. I can't use python 3.0. Is there a way to add allow_redirects to the request in python 2.7? I also can't use the requests library. I can use import requests.


#!/usr/bin/env python
import sys
import json
import httplib

# Retrieve list of errors from Error Viewer
def retrieve_errors_from_error_viewer(errors):
    headers = {"Content-Type": "application/json","Accept": "text/html"}
    data = {"dba": "XXX", "phase": "PROD"}
    conn = httplib.HTTPConnection('errorviewer.toys.net')
    conn.request('POST', '/api/errors', json.dumps(data), headers)
    response = conn.getresponse()
    print(str(response.status)+"  "+response.reason)
    print(response.read())


if __name__ == "__main__":
    # Retrieve Errors From ErrorViewer
    errors = []
    retrieve_errors_from_error_viewer(errors)

Solution

  • If you use httplib2 instead of httplib, you have the follow_all_redirects option that should solve your problem.