gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:24:07 25 4
gpt4 key购买 nike

我正在用这样的类编写一个 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)

如您所见,我正在使用 _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)

最佳答案

根据文档,在您的 header 中提供“连接”:“关闭”应该在收到响应后关闭连接。:

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

关于python - 使用 httplib2.Http() 对象时的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1248926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com