python – 使用httplib2.Http()对象时的最佳实践

前端之家收集整理的这篇文章主要介绍了python – 使用httplib2.Http()对象时的最佳实践前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个类似于此类的 pythonic Web API包装器
  1. import httplib2
  2. import urllib
  3.  
  4. class apiWrapper:
  5.  
  6. def __init__(self):
  7. self.http = httplib2.Http()
  8.  
  9. def _http(self,url,method,dict):
  10. '''
  11. Im using this wrapper arround the http object
  12. all the time inside the class
  13. '''
  14. params = urllib.urlencode(dict)
  15. response,content = self.http.request(url,params,method)

正如您所看到的,我正在使用_http()方法来简化与httplib2.Http()对象的交互.这个方法经常在类中调用,我想知道与这个对象交互的最佳方法是什么:

>在__init__中创建对象,然后在调用_http()方法时重用它(如上面的代码所示)
>或者为每次调用_http()方法方法内创建httplib2.Http()对象(如下面的代码示例所示)

  1. import httplib2
  2. import urllib
  3.  
  4.  
  5. class apiWrapper:
  6.  
  7. def __init__(self):
  8.  
  9. def _http(self,dict):
  10. '''Im using this wrapper arround the http object
  11. all the time inside the class'''
  12. http = httplib2.Http()
  13. params = urllib.urlencode(dict)
  14. response,content = http.request(url,method)

解决方法

如果重用连接,则应保留Http对象.似乎httplib2能够以你在第一个代码中使用它的方式重用连接,所以这看起来是一个很好的方法.

同时,从对httplib2代码的浅层检查来看,似乎httplib2不支持清理未使用的连接,甚至不知道服务器何时决定关闭它不再需要的连接.如果确实如此,它看起来像是httplib2中的一个错误 – 所以我宁愿使用标准库(httplib).

猜你在找的Python相关文章