Skip to content

Commit

Permalink
Catch socket timeouts and clear dead connection (refs httplib2#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
justinfx committed Aug 15, 2018
1 parent aa1b95b commit 1e08cff
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
10 changes: 9 additions & 1 deletion python2/httplib2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1929,6 +1929,8 @@ def request(
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''

try:
if headers is None:
headers = {}
Expand Down Expand Up @@ -2143,13 +2145,19 @@ def request(
cachekey,
)
except Exception as e:
isTimeout = isinstance(e, socket.timeout)
if isTimeout:
conn = self.connections.pop(conn_key, None)
if conn:
conn.close()

if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
elif isTimeout:
content = "Request Timeout"
response = Response(
{
Expand Down
26 changes: 26 additions & 0 deletions tests/test_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,32 @@ def handler(request):
assert response.reason.startswith("Request Timeout")


def test_timeout_subsequent():
class Handler(object):
number=0

@classmethod
def handle(cls, request):
# request.number is always 1 because of
# the new socket connection each time
cls.number += 1
if cls.number % 2 != 0:
time.sleep(0.6)
return tests.http_response_bytes(status=500)
return tests.http_response_bytes(status=200)

http = httplib2.Http(timeout=0.5)
http.force_exception_to_status_code = True

with tests.server_request(Handler.handle, request_count=2) as uri:
response, _ = http.request(uri)
assert response.status == 408
assert response.reason.startswith("Request Timeout")

response, _ = http.request(uri)
assert response.status == 200


def test_timeout_https():
c = httplib2.HTTPSConnectionWithTimeout("localhost", 80, timeout=47)
assert 47 == c.timeout
Expand Down

0 comments on commit 1e08cff

Please sign in to comment.