tags:

views:

22

answers:

0

My code makes a bunch of https calls using httplib. I want to re-use the httplib.py connection object, but if I do, I sometimes get CannotSendRequest exceptions because the connection ends up in a strange state because some other bit of code blows up mid-way through a request. So what I want is a way to cache the connection object such that if it's in a valid state we re-use it, but re-connect if it's not in a valid state. I don't see a public method on httplib.HTTPSConnection to tell me if the connection is in a valid state or not. And it's not easy for me to catch the CannotSendRequest exception because it could happen in lots of places in the code. So what I'd like to do is something like this:

CONNECTION_CACHE = None

def get_connection():
    global CONNECTION_CACHE 

    if (not CONNECTION_CACHE) or (CONNECTION_CACHE.__state != httlib._CS_IDLE):
        CONNECTION_CACHE = httplib.HTTPSConnection(SERVER)

    return CONNECTION_CACHE

but this fails because __state is private. Is there any way to do this? I could patch httplib to expose a is_in_valid_state() method, but I'd rather avoid patching the base python libraries if I can.