我正在编写一个类似于此类的pythonic Web API包装器
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)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在使用该_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)
Run Code Online (Sandbox Code Playgroud)
小智 7
提供"连接":标题中的"关闭"应根据文档在收到响应后关闭连接:
headers = {'connection': 'close'}
resp, content = h.request(url, headers=headers)
Run Code Online (Sandbox Code Playgroud)
如果重用连接,则应保留 Http 对象。看来 httplib2 能够像您在第一个代码中使用连接一样重用连接,因此这看起来是一个很好的方法。
同时,从对 httplib2 代码的浅层检查来看,httplib2 似乎不支持清理未使用的连接,甚至不支持服务器何时决定关闭它不再需要的连接。如果确实如此,那么对我来说,它看起来像是 httplib2 中的一个错误 - 所以我宁愿使用标准库 (httplib)。
| 归档时间: |
|
| 查看次数: |
5093 次 |
| 最近记录: |