Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple requests in a single connection?

Is it possible to put multiple requests without breaking the connection using python httplib?. Like, can I upload a big file to the server in parts but in a single socket connection.

I looked for answers. But nothing seemed so clear and definite.

Any examples/related links will be helpfull. Thanks.

like image 876
asdfg Avatar asked Jan 26 '26 21:01

asdfg


2 Answers

Yes, the connection stays open until you close it using the close() method.

The following example, taken from the httplib documentation, shows how to perform multiple requests using a single connection:

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()
like image 112
Pär Wieslander Avatar answered Jan 29 '26 11:01

Pär Wieslander


You need to be sure to call the .read() function on your response. Otherwise you'll get an error like:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    conn.request("GET", "/2.html")
  File "C:\Python27\lib\httplib.py", line 955, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 983, in _send_request
    self.putrequest(method, url, **skips)
  File "C:\Python27\lib\httplib.py", line 853, in putrequest
    raise CannotSendRequest()
CannotSendRequest

This exception is raised if the return data has not been read (even if no data is returned, or an HTTP error was recieved [a 404 for example]).

like image 43
Whyrat Avatar answered Jan 29 '26 11:01

Whyrat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!