繁体   English   中英

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

[英]Avoiding CannotSendRequest exceptions when re-using httplib.HTTPSConnection objects

我的代码使用httplib进行了一堆https调用。 我想重新使用httplib.py连接对象,但是如果这样做,我有时会收到CannotSendRequest异常,因为连接最终以一种奇怪的状态结束,因为其他一些代码在请求过程中被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库。

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

> 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是答案

在Python中,没有“私有”或“公共”之类的东西。 您的代码在其他地方失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM