Merge pull request #412 from seemethere/improving_performance

Header performance gains
This commit is contained in:
Eli Uriegas 2017-02-12 15:48:45 -06:00 committed by GitHub
commit bb3d48f98b

View File

@ -1,4 +1,3 @@
from collections import ChainMap
from mimetypes import guess_type from mimetypes import guess_type
from os import path from os import path
from ujson import dumps as json_dumps from ujson import dumps as json_dumps
@ -98,17 +97,15 @@ class HTTPResponse:
def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None): def output(self, version="1.1", keep_alive=False, keep_alive_timeout=None):
# This is all returned in a kind-of funky way # This is all returned in a kind-of funky way
# We tried to make this as fast as possible in pure python # We tried to make this as fast as possible in pure python
default_header = dict() timeout_header = b''
if keep_alive: if keep_alive and keep_alive_timeout is not None:
if keep_alive_timeout: timeout_header = b'Keep-Alive: %d\r\n' % keep_alive_timeout
default_header['Keep-Alive'] = keep_alive_timeout self.headers['Content-Length'] = self.headers.get(
default_header['Connection'] = 'keep-alive' 'Content-Length', len(self.body))
else: self.headers['Content-Type'] = self.headers.get(
default_header['Connection'] = 'close' 'Content-Type', self.content_type)
default_header['Content-Length'] = len(self.body)
default_header['Content-Type'] = self.content_type
headers = b'' headers = b''
for name, value in ChainMap(self.headers, default_header).items(): for name, value in self.headers.items():
try: try:
headers += ( headers += (
b'%b: %b\r\n' % ( b'%b: %b\r\n' % (
@ -117,6 +114,7 @@ class HTTPResponse:
headers += ( headers += (
b'%b: %b\r\n' % ( b'%b: %b\r\n' % (
str(name).encode(), str(value).encode('utf-8'))) str(name).encode(), str(value).encode('utf-8')))
# Try to pull from the common codes first # Try to pull from the common codes first
# Speeds up response rate 6% over pulling from all # Speeds up response rate 6% over pulling from all
status = COMMON_STATUS_CODES.get(self.status) status = COMMON_STATUS_CODES.get(self.status)
@ -124,11 +122,15 @@ class HTTPResponse:
status = ALL_STATUS_CODES.get(self.status) status = ALL_STATUS_CODES.get(self.status)
return (b'HTTP/%b %d %b\r\n' return (b'HTTP/%b %d %b\r\n'
b'Connection: %b\r\n'
b'%b'
b'%b\r\n' b'%b\r\n'
b'%b') % ( b'%b') % (
version.encode(), version.encode(),
self.status, self.status,
status, status,
b'keep-alive' if keep_alive else b'close',
timeout_header,
headers, headers,
self.body self.body
) )