From 70382f21baeea96765dd3d1fbd68817c948dfe34 Mon Sep 17 00:00:00 2001 From: Zhiwei Date: Sun, 26 Jun 2022 15:11:48 -0500 Subject: [PATCH] Fix and improve file cache control header calculation (#2486) --- sanic/compat.py | 4 +++- sanic/response.py | 9 +++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/sanic/compat.py b/sanic/compat.py index 880ca681..4ea2ed91 100644 --- a/sanic/compat.py +++ b/sanic/compat.py @@ -3,6 +3,8 @@ import os import signal import sys +from typing import Awaitable + from multidict import CIMultiDict # type: ignore @@ -51,7 +53,7 @@ use_trio = sys.argv[0].endswith("hypercorn") and "trio" in sys.argv if use_trio: # pragma: no cover import trio # type: ignore - def stat_async(path): + def stat_async(path) -> Awaitable[os.stat_result]: return trio.Path(path).stat() open_async = trio.open_file diff --git a/sanic/response.py b/sanic/response.py index 4b647003..b1765ed1 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -5,7 +5,7 @@ from email.utils import formatdate from functools import partial from mimetypes import guess_type from os import path -from pathlib import Path, PurePath +from pathlib import PurePath from time import time from typing import ( TYPE_CHECKING, @@ -22,7 +22,7 @@ from typing import ( ) from urllib.parse import quote_plus -from sanic.compat import Header, open_async +from sanic.compat import Header, open_async, stat_async from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE from sanic.cookies import CookieJar from sanic.exceptions import SanicException, ServerError @@ -340,9 +340,10 @@ async def file( ) if isinstance(last_modified, datetime): - last_modified = last_modified.timestamp() + last_modified = last_modified.replace(microsecond=0).timestamp() elif isinstance(last_modified, Default): - last_modified = Path(location).stat().st_mtime + stat = await stat_async(location) + last_modified = stat.st_mtime if last_modified: headers.setdefault(