2009-08-08 31 views
6

我正在寫一個Python的網絡A​​PI包裝有一類這樣的最佳實踐使用時的httplib2.Http()對象

import httplib2 
import urllib 

class apiWrapper: 

    def __init__(self): 
     self.http = httplib2.Http() 

    def _http(self, url, method, dict): 
     ''' 
     Im using this wrapper arround the http object 
     all the time inside the class 
     ''' 
     params = urllib.urlencode(dict) 
     response, content = self.http.request(url,params,method) 

,你可以看到我使用的方法_http()簡化與httplib2.Http()對象的交互。這種方法是在類中調用非常頻繁,我想知道什麼是與該對象交互的最佳方法:

  • 創建的對象的__init__然後重用它時,被稱爲_http()方法(如在上述的代碼)
  • 所示或創建該方法內的物體httplib2.Http()_http()方法(每個呼叫如下的代碼示例所示

import httplib2 
import urllib 


class apiWrapper: 

    def __init__(self): 

    def _http(self, url, method, dict): 
     '''Im using this wrapper arround the http object 
     all the time inside the class''' 
     http = httplib2.Http() 
     params = urllib.urlencode(dict) 
     response, content = http.request(url,params,method) 

回答

2

如果您重新使用連接,則應該保留Http對象。看來httplib2能夠在你的第一個代碼中使用它的方式重用連接,所以這看起來是一個好方法。

同時,從httplib2代碼的淺層檢查看來,似乎httplib2不支持清理未使用的連接,或者甚至在服務器決定關閉不再需要的連接時發現。如果確實如此,那麼它就像是一個httplib2中的bug,所以我寧願使用標準庫(httplib)。

7

直供「連接」:「關閉」在你的標題應根據文檔關閉接收到響應後,連接:

headers = {'connection': 'close'} 
resp, content = h.request(url, headers=headers)