【问题标题】:Avoiding CannotSendRequest exceptions when re-using httplib.HTTPSConnection objects重用 httplib.HTTPSConnection 对象时避免 CannotSendRequest 异常
【发布时间】:2010-07-26 18:44:26
【问题描述】:

我的代码使用 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 库。

【问题讨论】:

    标签: python https


    【解决方案1】:

    (触摸私有属性是个坏主意,建议观看者酌情决定。)

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2010-09-29
        • 2014-03-29
        • 1970-01-01
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 2012-05-24
        • 1970-01-01
        • 2013-09-04
        相关资源
        最近更新 更多