From 3f8cfb4977920a4a68a943911a6e9c8a44b82768 Mon Sep 17 00:00:00 2001 From: Zhiwei Liang Date: Mon, 16 May 2022 01:29:51 -0500 Subject: [PATCH] Change to HTTP standard headers --- sanic/response.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/sanic/response.py b/sanic/response.py index df2d8230a0..7f7cf83e14 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -62,6 +62,7 @@ class BaseHTTPResponse: "status", "headers", "_cookies", + "auto_content_length", ) _dumps = json_dumps @@ -74,6 +75,7 @@ def __init__(self): self.status: int = None self.headers = Header({}) self._cookies: Optional[CookieJar] = None + self.auto_content_length = False def _encode_body(self, data: Optional[AnyStr]): if data is None: @@ -153,6 +155,8 @@ async def send( if hasattr(data, "encode") else data or b"" ) + if self.auto_content_length and "content-length" not in self.headers: + self.headers["content-length"] = len(data) await self.stream.send(data, end_stream=end_stream) @@ -178,6 +182,7 @@ def __init__( status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: Optional[str] = None, + auto_content_length: bool = False, ): super().__init__() @@ -186,6 +191,7 @@ def __init__( self.status = status self.headers = Header(headers or {}) self._cookies = None + self.auto_content_length = auto_content_length async def eof(self): await self.send("", True) @@ -337,12 +343,11 @@ async def file( last_modified = stat.st_mtime if not max_age: max_age = 10 # Should change this (default) value to configable? - headers.setdefault("file_size", stat.st_size) if last_modified: - headers.setdefault("last_modified", last_modified) + headers.setdefault("last-modified", last_modified) if max_age: - headers.setdefault("max_age", max_age) + headers.setdefault("cache-control", f"max-age={max_age}") filename = filename or path.split(location)[-1] @@ -363,6 +368,7 @@ async def file( status=status, headers=headers, content_type=mime_type, + auto_content_length=True, )