duck.http.core.response_finalizer

Module containing ResponseFinalizer class focusing on putting on the final touches to the response.

The final touches include:

  • Content compression.

  • Content length calculation and insertion.

  • Content encoding determination and insertion.

  • etc.

Module Contents

Classes

AsyncResponseFinalizer

Asynchronous ResponseFinalizer class focusing on putting on the final touches to the response.

ResponseFinalizer

ResponseFinalizer class focusing on putting on the final touches to the response.

Functions

set_compressable_iter_content

Modifies the response iter_content methods with new functions to compress data as were are iterating.

Data

CUSTOM_TEMPLATES

async_response_finalizer

response_finalizer

API

class duck.http.core.response_finalizer.AsyncResponseFinalizer[source]

Bases: duck.http.core.response_finalizer.ResponseFinalizer

Asynchronous ResponseFinalizer class focusing on putting on the final touches to the response.

async do_content_compression(response, request) None

Compresses the content if the client supports it and if the content is not a streaming response. (if necessary).

async do_set_streaming_range(response, request)

Set streaming range attributes on StreamingRangeHttpResponse. This method parses the ‘Range’ header from the request and sets the start and end positions for partial content streaming.

If an If-Range header is present and does not match the response’s current strong validator (ETag, falling back to Last-Modified), the Range header is ignored entirely and the full resource is served as 200, since splicing a partial range against a changed resource would silently corrupt the client’s reconstructed file.

Parameters:
  • response – The response object to set streaming range on.

  • request – The incoming HTTP request containing the ‘Range’ header.

Raises:

ValueError – If the ‘Range’ header is malformed or invalid.

async finalize_response(response: duck.http.response.HttpResponse, request: duck.http.request.HttpRequest, do_set_streaming_range: bool = True, do_content_compression: bool = True)[source]

Puts the final touches to the response.

duck.http.core.response_finalizer.CUSTOM_TEMPLATES: Dict[int, Callable]

None

class duck.http.core.response_finalizer.ResponseFinalizer[source]

ResponseFinalizer class focusing on putting on the final touches to the response.

do_content_compression(response, request) None

Compresses the content if the client supports it and if the content is not a streaming response. (if necessary).

do_request_response_transformation(response: duck.http.response.HttpResponse, request: duck.http.request.HttpRequest) bool

Transforms the response object by applying request- and response-based modifications.

This includes, but is not limited to, header changes and body alterations.

Behavior Examples:

  • If the request method is HEAD, the response body is replaced with empty bytes.

  • If a matching template is found in the CUSTOM_TEMPLATES configuration, the entire response may be replaced.

  • If the response is downgraded to 304 Not Modified, further response processing (e.g. body generation, streaming setup) should be skipped by the caller.

Parameters:
  • response – The original response to be transformed.

  • request – The incoming HTTP request associated with the response.

Returns:

True if the caller should continue normal response processing, False if processing should stop here (e.g. the response was downgraded to 304 Not Modified and has nothing further to do).

Return type:

bool

do_set_connection_mode(response, request) None

Sets the response connection mode according to the HTTP version, client request, and server connection-mode configuration.

HTTP/1.1 uses persistent connections by default, while HTTP/1.0 requires an explicit Connection: keep-alive header.

The server’s configured connection mode can restrict persistent connections, but cannot force a client to keep a connection open when the client explicitly requests Connection: close.

Parameters:
  • response – HTTP response whose Connection header should be set.

  • request – HTTP request associated with the response.

do_set_content_headers(response, request) None

Sets the appropriate content headers like Content-Type, Content-Encoding & Content-Length if not set.

Notes:

  • If response is an instance of StreamingHttpResponse, the Content-Length header is removed as a safe measure. The size of the response content can become unpredictable especially when data is compressed as it is being sent.

do_set_extra_headers(response, request) None

Sets extra headers like Date, Cache-Control and other internal headers.

do_set_fixed_headers(response, request) None

Sets fixed headers from settings, i.e. extra headers, cors headers and security headers.

do_set_streaming_range(response, request)

Set streaming range attributes on StreamingRangeHttpResponse. This method parses the ‘Range’ header from the request and sets the start and end positions for partial content streaming.

If an If-Range header is present and does not match the response’s current strong validator (ETag, falling back to Last-Modified), the Range header is ignored entirely and the full resource is served as 200, since splicing a partial range against a changed resource would silently corrupt the client’s reconstructed file.

Parameters:
  • response – The response object to set streaming range on.

  • request – The incoming HTTP request containing the ‘Range’ header.

Raises:

ValueError – If the ‘Range’ header is malformed or invalid.

static downgrade_to_not_modified(response: duck.http.response.HttpResponse) None[source]

Converts a fully-built 200/206 response in place into a 304.

Strips the body and any representation-specific headers (since a 304 has no body), while preserving the validators (ETag is kept; Last-Modified remains unemitted as always) so the client can keep using its cached copy.

Parameters:

response – The response to downgrade. Mutated in place.

finalize_response(response: duck.http.response.HttpResponse, request: duck.http.request.HttpRequest, do_set_streaming_range: bool = True, do_content_compression: bool = True)[source]

Puts the final touches to the response.

static is_not_modified(request: duck.http.request.HttpRequest, etag: Optional[str], last_modified: Optional[str]) bool[source]

Determines whether a request’s conditional headers match the response’s validators.

If-None-Match (ETag) is authoritative and checked first, since it is precise to the nanosecond via FileIOStream.etag. If-Modified-Since is only consulted as a fallback when the client sent no If-None-Match — it is never used to override a mismatching ETag, and Last-Modified is never read from response headers here since it is intentionally never emitted (see HttpResponseBase.finalize_headers); this compares against the response’s internal last_modified value instead.

Parameters:
  • request – The incoming request, inspected for If-None-Match / If-Modified-Since headers.

  • etag – The response’s current ETag, or None.

  • last_modified – The response’s current Last-Modified value (HTTP-date string), or None.

Returns:

True if the client’s cached copy is still valid and a 304 should be sent instead of the body.

static is_range_valid(request: duck.http.request.HttpRequest, etag: Optional[str], last_modified: Optional[str]) bool[source]

Determines whether a Range request should be honored, per If-Range.

If-Range (RFC 7233 §3.2) lets a client say “give me just this byte range, but only if the resource I have cached is still exactly this version — otherwise send me the whole thing.” If no If-Range header is present, Range is always honored (this returns True).

Unlike If-None-Match, If-Range requires a strong comparison — a weak validator (W/"...") never satisfies it, even if the underlying value is identical, since a weak ETag only promises semantic equivalence, not byte-for-byte identity, which is unsafe to splice a partial range into. If the header value doesn’t look like an ETag (no surrounding quotes), it’s treated as an HTTP-date and compared against last_modified instead.

Parameters:
  • request – The incoming request, inspected for the If-Range header.

  • etag – The response’s current (strong) ETag, or None.

  • last_modified – The response’s current Last-Modified value (HTTP-date string), or None. Used only when If-Range carries a date rather than an ETag.

Returns:

True if Range should be honored (no If-Range sent, or it matches the current strong validator). False if the resource has changed and the full body should be sent instead.

duck.http.core.response_finalizer.async_response_finalizer

‘AsyncResponseFinalizer(…)’

duck.http.core.response_finalizer.response_finalizer

‘ResponseFinalizer(…)’

duck.http.core.response_finalizer.set_compressable_iter_content(response)[source]

Modifies the response iter_content methods with new functions to compress data as were are iterating.

Note:

  • Only use this function if response data is compressable.

  • This function modifies both sync and async version of iter_content, i.e. iter_content and async_iter_content.