improve performance

This commit is contained in:
Suby Raman
2017-02-21 11:28:45 -05:00
parent 4e8aac4b41
commit 8b23dec322
2 changed files with 58 additions and 17 deletions

View File

@@ -162,27 +162,61 @@ class HttpProtocol(asyncio.Protocol):
self.request.body = b''.join(self.request.body)
self._request_handler_task = self.loop.create_task(
self.request_handler(self.request, self.write_response))
self.request_handler(
self.request,
self.write_response,
self.stream_response))
# -------------------------------------------- #
# Responding
# -------------------------------------------- #
async def write_response(self, response):
def write_response(self, response):
"""
Writes response content synchronously to the transport.
"""
try:
keep_alive = (
self.parser.should_keep_alive() and not self.signal.stopped)
if isinstance(response, StreamingHTTPResponse):
# streaming responses should have direct write access to the
# transport
response.transport = self.transport
await response.stream(
self.request.version, keep_alive, self.request_timeout)
self.transport.write(
response.output(
self.request.version, keep_alive,
self.request_timeout))
except AttributeError:
log.error(
('Invalid response object for url {}, '
'Expected Type: HTTPResponse, Actual Type: {}').format(
self.url, type(response)))
self.write_error(ServerError('Invalid response type'))
except RuntimeError:
log.error(
'Connection lost before response written @ {}'.format(
self.request.ip))
except Exception as e:
self.bail_out(
"Writing response failed, connection closed {}".format(
repr(e)))
finally:
if not keep_alive:
self.transport.close()
else:
self.transport.write(
response.output(
self.request.version, keep_alive,
self.request_timeout))
self._last_request_time = current_time
self.cleanup()
async def stream_response(self, response):
"""
Streams a response to the client asynchronously. Attaches
the transport to the response so the response consumer can
write to the response as needed.
"""
try:
keep_alive = (
self.parser.should_keep_alive() and not self.signal.stopped)
response.transport = self.transport
await response.stream(
self.request.version, keep_alive, self.request_timeout)
except AttributeError:
log.error(
('Invalid response object for url {}, '