2010-07-26 61 views
1

我的代碼使用httplib進行了一堆https調用。我想重新使用httplib.py連接對象,但如果這樣做,我有時會遇到CannotSendRequest例外情況,因爲連接會以奇怪的狀態結束,因爲其他一些代碼會在請求中途中斷。所以我想要的是一種緩存連接對象的方法,如果它處於有效狀態,我們重新使用它,但如果它不處於有效狀態,則重新連接。我沒有看到httplib.HTTPSConnection上的公開方法告訴我連接是否處於有效狀態。對於我來說,捕獲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庫,如果可以的話。

回答

-3

在Python中,沒有「私人」或「公共」之類的東西。你的代碼在別的地方失敗了。

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