开发者

Avoiding CannotSendRequest exceptions when re-using httplib.HTTPSConnection objects

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.


(Touching private attribute is a bad idea, viewer discretion is advised.)

> Private name mangling: When an identifier that textually occurs in a
> class definition begins with two or more underscore characters and
> does not end in two or more underscores, it is considered a private
> name of that class. Private names are transformed to a longer form
> before code is generated for them. The transformation inserts the
> class name in front of the name, with leading underscores removed, and
> a single underscore inserted in front of the class name. For example,
> the identifier __spam occurring in a class named Ham will be
> transformed to _Ham__spam. This transformation is independent of the
> syntactical context in which the identifier is used. If the
> transformed name is extremely long (longer than 255 characters),
> implementation defined truncation may happen. If the class name
> consists only of underscores, no transformation is done.

Thus conn._HTTPSConnection__state is the answer


In Python there is no such thing as "private" or "public". Your code is failing somewhere else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜