重新使用httplib.HTTPSConnection对象时避免使用CannotSendRequest异常

时间:2010-07-26 18:44:26

标签: python https

我的代码使用httplib进行一堆https调用。我想重新使用httplib.py连接对象,但如果我这样做,我有时会得到CannotSendRequest异常,因为连接最终处于一个奇怪的状态,因为其他一些代码在请求中途爆炸。所以我想要的是一种缓存连接对象的方法,如果它处于有效状态,我们重新使用它,但如果它不在有效状态,则重新连接。我没有看到httplib.HTTPSConnection上的公共方法告诉我连接是否处于有效状态。我抓住CannotSendRequest异常并不容易,因为它可能发生在代码中的很多地方。所以我想做的是这样的事情:

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

但由于__state是私有的,因此失败。有没有办法做到这一点?我可以修补httplib来公开is_in_valid_state()方法,但如果可以的话,我宁愿避免修补基础python库。

2 个答案:

答案 0 :(得分:0)

(触摸私人属性是一个坏主意,建议观众自行决定。)

> 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.

因此conn._HTTPSConnection__state就是答案

答案 1 :(得分:-3)

在Python中没有“私有”或“公共”这样的东西。你的代码在其他地方失败了。