Best practice when using the httplib2.Http () object

I am writing a pythonic web API wrapper with such a class

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) 

as you can see, I am using the _http() method to simplify the interaction with the httplib2.Http() object. This method is often found inside a class, and I wonder how best to interact with this object:

  • create an object in __init__ and then reuse when the _http() method is called (as shown in the code above )
  • or create an httplib2.Http() object inside the method for each call to the _http() method (as shown in the code example below )

 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) 
+6
python
source share
2 answers

You must save the Http object if you are reusing connections. It seems that httplib2 is able to reuse connections the way you use it in your first code, so this seems like a good approach.

At the same time, from a small verification of the httplib2 code, it seems that httplib2 does not support cleaning up unused connections or even notices when the server decided to close the connection that it no longer wants. If this is true, this seems like an error in httplib2 for me, so I would rather use the standard library (httplib).

+2
source

Delivery of "connection": "close" in your headers should, according to the document, close the connection after receiving a response .:

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

All Articles