Search code examples
pythonhttplib

python: printing information about BadStatusLine error


I'm getting a BadStatusLine after executing the following python script. How can I print details about the BadStatusLine?

#!/usr/bin/python

import urllib
import urllib2
import httplib


try:
    # NoActiveDevsPerQtr
    request = urllib2.Request('http://127.0.0.1:8090')

    request.add_header('Accept',        'text/csv')
    request.add_header('User-Agent',    'python-script')

    request.add_data("""
        <? xml version="1.0"?>
        <log_query>
            <querytype>ListPerQtr</querytype>
            <year>2014</year>
            <quarter>3</quarter>
        </log_query>
    """)


    response = urllib2.urlopen(request)
    content  = response.read()
    print content

except httplib.BadStatusLine as e:
    print e

print e is printing nothing.

As requested, the actual error being thrown when I remove the except httplib.BadStatusLine is as follows:

Traceback (most recent call last):
File "./IQueryTests.py", line 25, in <module>
response = urllib2.urlopen(request)
File "/usr/lib64/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib64/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib64/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib64/python2.6/urllib2.py", line 1190, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib64/python2.6/urllib2.py", line 1163, in do_open
r = h.getresponse()
File "/usr/lib64/python2.6/httplib.py", line 990, in getresponse
response.begin()
File "/usr/lib64/python2.6/httplib.py", line 391, in begin
version, status, reason = self._read_status()
File "/usr/lib64/python2.6/httplib.py", line 355, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine

Solution

  • The source ('httplib.py') says this in one case where it raises 'BadStatusLine' :

            if not line:
            # Presumably, the server closed the connection before
            # sending a valid response.
            raise BadStatusLine(line)
    

    Perhaps you are hitting this case, implying that line is null or empty.

    Source: https://hg.python.org/cpython/file/2.7/Lib/httplib.py

    This looks like a tired programmer decision; it would be better to define another exception, something like 'NoStatusLine'