if sys.version_info < (3, 9):
CONTENT_TYPES.encodings_map[".br"] = "br"
# File extension to IANA encodings map that will be checked in the order defined.
ENCODING_EXTENSIONS = MappingProxyType(
{ext: CONTENT_TYPES.encodings_map[ext] for ext in (".br", ".gz")}
)
# Provide additional MIME type/extension pairs to be recognized. # https://en.wikipedia.org/wiki/List_of_archive_formats#Compression_only
ADDITIONAL_CONTENT_TYPES = MappingProxyType(
{ "application/gzip": ".gz", "application/x-brotli": ".br", "application/x-bzip2": ".bz2", "application/x-compress": ".Z", "application/x-xz": ".xz",
}
)
# Add custom pairs and clear the encodings map so guess_type ignores them.
CONTENT_TYPES.encodings_map.clear() for content_type, extension in ADDITIONAL_CONTENT_TYPES.items():
CONTENT_TYPES.add_type(content_type, extension) # type: ignore[attr-defined]
class FileResponse(StreamResponse): """A response object can be used to send files."""
def _get_file_path_stat_encoding(
self, accept_encoding: str
) -> Tuple[pathlib.Path, os.stat_result, Optional[str]]: """Return the file path, stat result, and encoding.
If an uncompressed file is returned, the encoding is set to
:py:data:`None`.
This method should be called from a thread executor
since it calls os.stat which may block. """
file_path = self._path for file_extension, file_encoding in ENCODING_EXTENSIONS.items(): if file_encoding notin accept_encoding: continue
compressed_path = file_path.with_suffix(file_path.suffix + file_extension) with suppress(OSError): # Do not follow symlinks and ignore any non-regular files.
st = compressed_path.lstat() if S_ISREG(st.st_mode): return compressed_path, st, file_encoding
# Fallback to the uncompressed file return file_path, file_path.stat(), None
async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]:
loop = asyncio.get_running_loop() # Encoding comparisons should be case-insensitive # https://www.rfc-editor.org/rfc/rfc9110#section-8.4.1
accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() try:
file_path, st, file_encoding = await loop.run_in_executor( None, self._get_file_path_stat_encoding, accept_encoding
) except OSError: # Most likely to be FileNotFoundError or OSError for circular # symlinks in python >= 3.13, so respond with 404.
self.set_status(HTTPNotFound.status_code) return await super().prepare(request)
# Forbid special files like sockets, pipes, devices, etc. ifnot S_ISREG(st.st_mode):
self.set_status(HTTPForbidden.status_code) return await super().prepare(request)
modsince = request.if_modified_since if (
modsince isnotNone and ifnonematch isNone and st.st_mtime <= modsince.timestamp()
): return await self._not_modified(request, etag_value, last_modified)
status = self._status
file_size = st.st_size
count = file_size
start = None
ifrange = request.if_range if ifrange isNoneor st.st_mtime <= ifrange.timestamp(): # If-Range header check: # condition = cached date >= last modification date # return 206 if True else 200. # if False: # Range header would not be processed, return 200 # if True but Range header missing # return 200 try:
rng = request.http_range
start = rng.start
end = rng.stop except ValueError: # https://tools.ietf.org/html/rfc7233: # A server generating a 416 (Range Not Satisfiable) response to # a byte-range request SHOULD send a Content-Range header field # with an unsatisfied-range value. # The complete-length in a 416 response indicates the current # length of the selected representation. # # Will do the same below. Many servers ignore this and do not # send a Content-Range header with HTTP 416
self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}"
self.set_status(HTTPRequestRangeNotSatisfiable.status_code) return await super().prepare(request)
# If a range request has been made, convert start, end slice # notation into file pointer offset and count if start isnotNoneor end isnotNone: if start < 0 and end isNone: # return tail of file
start += file_size if start < 0: # if Range:bytes=-1000 in request header but file size # is only 200, there would be trouble without this
start = 0
count = file_size - start else: # rfc7233:If the last-byte-pos value is # absent, or if the value is greater than or equal to # the current length of the representation data, # the byte range is interpreted as the remainder # of the representation (i.e., the server replaces the # value of last-byte-pos with a value that is one less than # the current length of the selected representation).
count = (
min(end if end isnotNoneelse file_size, file_size) - start
)
if start >= file_size: # HTTP 416 should be returned in this case. # # According to https://tools.ietf.org/html/rfc7233: # If a valid byte-range-set includes at least one # byte-range-spec with a first-byte-pos that is less than # the current length of the representation, or at least one # suffix-byte-range-spec with a non-zero suffix-length, # then the byte-range-set is satisfiable. Otherwise, the # byte-range-set is unsatisfiable.
self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}"
self.set_status(HTTPRequestRangeNotSatisfiable.status_code) return await super().prepare(request)
status = HTTPPartialContent.status_code # Even though you are sending the whole file, you should still # return a HTTP 206 for a Range request.
self.set_status(status)
# If the Content-Type header is not already set, guess it based on the # extension of the request path. The encoding returned by guess_type # can be ignored since the map was cleared above. if hdrs.CONTENT_TYPE notin self.headers:
self.content_type = (
CONTENT_TYPES.guess_type(self._path)[0] or FALLBACK_CONTENT_TYPE
)
if file_encoding:
self.headers[hdrs.CONTENT_ENCODING] = file_encoding
self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING # Disable compression if we are already sending # a compressed file since we don't want to double # compress.
self._compression = False
if status == HTTPPartialContent.status_code:
self.headers[hdrs.CONTENT_RANGE] = "bytes {}-{}/{}".format(
real_start, real_start + count - 1, file_size
)
# If we are sending 0 bytes calling sendfile() will throw a ValueError if count == 0 or must_be_empty_body(request.method, self.status): return await super().prepare(request)
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.53Bemerkung:
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.