@@ -188,16 +188,15 @@ def request(self, method, url, bodyData, headers):
188188 if 'content-type' in headers :
189189 del headers ['content-type' ]
190190
191- #TODO: Context manager
192- requestBody = RequestBody (bodyData , headers )
193- conn = self .get_connection ()
194- conn .request (method , url , requestBody .process (), headers )
195- response = conn .getresponse ()
196- status = response .status
197- content = ResponseBody (response )
198- self .headers = response .getheaders ()
199-
200- conn .close ()
191+ # Context manager to handle requests
192+ with connectionManager (self ) as conn :
193+ requestBody = RequestBody (bodyData , headers )
194+ conn .request (method , url , requestBody .process (), headers )
195+ response = conn .getresponse ()
196+ status = response .status
197+ content = ResponseBody (response )
198+ self .headers = response .getheaders ()
199+
201200 return status , content .processBody ()
202201
203202 def _fix_headers (self , headers ):
@@ -411,3 +410,19 @@ def _filterEmptyHeaders(self, headers):
411410 newHeaders [header ] = headers [header ]
412411
413412 return newHeaders
413+
414+ class connectionManager (object ):
415+ '''
416+ Context manager for handling connections in client.request
417+ '''
418+ def __init__ (self , client ):
419+ self .conn = client .get_connection ()
420+
421+ def __enter__ (self ):
422+ return self .conn
423+
424+ def __exit__ (self , exc_type , exc_value , traceback ):
425+ self .conn .close ()
426+
427+
428+
0 commit comments