Search code examples
pythonconnectionhttplib

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.


Solution

  • 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()