"""静态文件响应:容忍媒体元素发出的异常 Range 头(#416 / #400)。""" import os from pathlib import Path from starlette.datastructures import Headers from starlette.responses import FileResponse from starlette.types import Receive, Scope, Send class RangeSafeFileResponse(FileResponse): """不可满足或无法解析的 Range 头退化为整文件 200 响应。 浏览器视频元素偶尔会发出 ``Range: bytes=12345-`` 这类超出文件长度的请求, Starlette 会回 416,部分浏览器随即报错。这里只在可满足时走正常的 206 分段。 """ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] != "http" or "range" not in Headers(scope=scope): await super().__call__(scope, receive, send) return if self.stat_result is None: self.stat_result = os.stat(self.path) self.set_stat_headers(self.stat_result) try: FileResponse._parse_range_header(Headers(scope=scope)["range"], self.stat_result.st_size) except Exception: scope = dict(scope) raw = list(scope["headers"]) scope["headers"] = [(name, value) for name, value in raw if name.lower() not in (b"range", b"if-range")] await super().__call__(scope, receive, send) def range_safe_file(path: Path, media_type: str | None = None, filename: str | None = None, stat_result=None, content_disposition_type: str = "attachment") -> FileResponse: return RangeSafeFileResponse(path, media_type=media_type, filename=filename, stat_result=stat_result, content_disposition_type=content_disposition_type)