From: Pierce Lopez Date: Mon, 5 Jun 2017 04:48:45 +0000 (-0400) Subject: http1connection: add "Connection: close" header if appropriate X-Git-Tag: v5.0.0~74^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e7cb79779582bc4a27062795ab401adbf1faea57;p=thirdparty%2Ftornado.git http1connection: add "Connection: close" header if appropriate When HTTP1Connection acts as the server, it closes the connection after writing the response if the client includes the "Connection: close" header in the request, or if the `no_keep_alive` option is set to True in the constructor. According to https://tools.ietf.org/html/rfc7230#section-6.6 > The server SHOULD send a "close" connection option in its final response on that connection. It was possible for an Application to set the Connection header appropriately. But it is very helpful for tornado to take care of this automatically, particularly if "close" was specified in a request header. --- diff --git a/tornado/http1connection.py b/tornado/http1connection.py index c6d3e336f..b7a62b8c0 100644 --- a/tornado/http1connection.py +++ b/tornado/http1connection.py @@ -357,6 +357,10 @@ class HTTP1Connection(httputil.HTTPConnection): # Applications are discouraged from touching Transfer-Encoding, # but if they do, leave it alone. 'Transfer-Encoding' not in headers) + # If connection to a 1.1 client will be closed, inform client + if (self._request_start_line.version == 'HTTP/1.1' and + self._disconnect_on_finish): + headers['Connection'] = 'close' # If a 1.0 client asked for keep-alive, add the header. if (self._request_start_line.version == 'HTTP/1.0' and (self._request_headers.get('Connection', '').lower() == @@ -418,7 +422,7 @@ class HTTP1Connection(httputil.HTTPConnection): def write(self, chunk, callback=None): """Implements `.HTTPConnection.write`. - For backwards compatibility is is allowed but deprecated to + For backwards compatibility it is allowed but deprecated to skip `write_headers` and instead call `write()` with a pre-encoded header block. """ diff --git a/tornado/test/httpserver_test.py b/tornado/test/httpserver_test.py index f5f91a9df..d8342f748 100644 --- a/tornado/test/httpserver_test.py +++ b/tornado/test/httpserver_test.py @@ -719,6 +719,7 @@ class KeepAliveTest(AsyncHTTPTestCase): self.stream.read_until_close(callback=self.stop) data = self.wait() self.assertTrue(not data) + self.assertEqual(self.headers['Connection'], 'close') self.close() # keepalive is supported for http 1.0 too, but it's opt-in