From e134cffa2af9d7da5680a7de18994ccdba4989f3 Mon Sep 17 00:00:00 2001 From: nggit <12218311+nggit@users.noreply.github.com> Date: Fri, 13 Oct 2023 13:32:43 +0700 Subject: [PATCH] optimize sendfile, avoid large read size --- tremolo/lib/http_response.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tremolo/lib/http_response.py b/tremolo/lib/http_response.py index 23f8e68..4decc96 100644 --- a/tremolo/lib/http_response.py +++ b/tremolo/lib/http_response.py @@ -242,7 +242,7 @@ async def write(self, data, buffer_size=16 * 1024, **kwargs): async def sendfile( self, path, - buffer_size=16384, + buffer_size=16 * 1024, content_type=b'application/octet-stream' ): try: @@ -341,9 +341,12 @@ async def sendfile( b'Content-Range', b'bytes %d-%d/%d' % ( start, end, file_size) ) - handle.seek(start) - await self.write(handle.read(size), chunked=False) + + while size > 0: + await self.write(handle.read(min(size, buffer_size)), + chunked=False) + size -= buffer_size else: client = self._request.client @@ -369,9 +372,13 @@ async def sendfile( b'Content-Range: bytes %d-%d/%d\r\n\r\n' % ( boundary, content_type, start, end, file_size) ) - handle.seek(start) - await self.write(b'%s\r\n' % handle.read(size)) + + while size > 0: + await self.write(handle.read(min(size, buffer_size))) + size -= buffer_size + + await self.write(b'\r\n') await self.write(b'--%s--\r\n' % boundary) await self.write(b'')