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

6 投票
2 回答
5587 浏览
提问于 2025-04-15 13:27

我正在写一个用Python做的网络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)

你可以看到,我使用了_http()这个方法来简化与httplib2.Http()对象的交互。这个方法在类里面被调用得很频繁,所以我在想,和这个对象互动的最佳方式是什么:

  • 是在__init__里创建这个对象,然后在调用_http()方法时重复使用它(就像上面的代码所示)
  • 还是在每次调用_http()方法时,直接在方法里创建httplib2.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 个回答

7

根据文档,如果在你的请求头中添加 'connection': 'close',那么在收到响应后,连接就会被关闭。

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

如果你想重复使用连接,就应该保留Http对象。看起来httplib2可以像你在第一段代码中那样重复使用连接,所以这个方法看起来不错。

不过,从我简单看了一下httplib2的代码,似乎它并没有处理未使用的连接,也不能察觉到服务器什么时候决定关闭一个不再需要的连接。如果真是这样的话,我觉得这算是httplib2的一个bug——所以我更倾向于使用标准库(httplib)。

撰写回答