duck.http.response¶
Module for representing Duck HttpResponses
Module Contents¶
Classes¶
Response object to represent raw response |
|
HTTP response that streams the rendered output of an HTML component. |
|
Class representing an http file response |
|
Class representing an http bad gateway response. |
|
Class representing an http bad request response. |
|
Class representing an http bad request syntax response. |
|
Class epresenting an http error response. |
|
Class representing an http forbidden request response. |
|
Class representing an http method not allowed response. |
|
Class representing an http not found response. |
|
Class representing an http range not satisfiable response. |
|
Class representing an http redirect response. |
|
Class representing an http request timeout response. |
|
Class representing an http response. |
|
Class representing an http server error response. |
|
Class representing an HTTP response for switching protocols (101 Switching Protocols). |
|
Class to representing an http too many requests response. |
|
Class representing an http unsupported version response. |
|
Class epresenting an json response. |
|
Class representing an HTTP streaming response. |
|
A subclass of StreamingHttpResponse designed to handle HTTP responses that support partial content (range requests), allowing clients to request specific byte ranges of the response content. This is useful for handling large files and enabling features like resuming downloads or streaming media. |
|
TemplateResponse class representing an http template response. |
Data¶
API¶
- class duck.http.response.BaseResponse(payload_obj: duck.http.response_payload.HttpResponsePayload, content_obj: Optional[duck.http.content.Content] = None)¶
Response object to represent raw response
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- __repr__()¶
- property content: bytes¶
Returns the content for the response.
- property content_encoding: str¶
Returns the content encoding for the response.
Notes:
This is not retrieved from headers but directly from the content object.
- property content_length: int¶
Returns the content length for the response.
… admonition:: Notes
This is not retrieved from headers but directly from the content object.
- property content_type: str¶
Returns the content type for the response.
Notes:
This is not retrieved from headers but directly from the content object.
- property cookies: http.cookies.SimpleCookie¶
Property getter for cookies. If not already initialized, it initializes the cookies.
- Returns:
The cookies for the response.
- Return type:
SimpleCookie
- delete_cookie(key: str, path: str = '/', domain: Optional[str] = None) None¶
Delete a cookie from the HttpResponse by setting its expiration date to the past. This will prompt the client to remove the cookie.
- Parameters:
key – The name of the cookie to delete.
path – The path for which the cookie was set. Defaults to “/”.
domain – The domain for which the cookie was set. Defaults to None.
- delete_header(header: str, failsafe: bool = True)¶
Deletes a header and if failsafe is True, no error will be raised if header doesn’t exist
- get_all_cookies() Dict[str, str]¶
Retrieves all cookies as a dictionary.
- Returns:
A dictionary of all cookies, where the key is the cookie name and the value is the cookie value.
- Return type:
Dict[str, str]
- get_cookie(name: str) str¶
Retrieves the value of a specific cookie by name.
- Parameters:
name – The name of the cookie to retrieve.
- Returns:
The cookie value, or an empty string if the cookie does not exist.
- Return type:
str
- get_cookie_obj(name: str) Optional[http.cookies.Morsel]¶
Retrieves the cookie object/morsel of a specific cookie by name.
- Parameters:
name – The name of the cookie to retrieve.
- Returns:
The cookie object, or None if the cookie does not exist.
- Return type:
Optional[Morsel]
- get_cookie_str(name: str, include_cookie_name: bool = True) str¶
Returns the cookie string for the provided name with all fields including max-age, domain, path, etc.
- Parameters:
include_cookie_name – Whether to cookie name e.g.
cookie=something;. Defaults to True.
- get_header(header: str, default_value: Optional = None) Optional[str]¶
Returns the case-insensitive header value or fallback to default value if not found.
- property headers: duck.http.headers.Headers¶
Return the current response headers.
- property raw: bytes¶
Retrieve the raw response data as a bytes object.
This method returns the full response content (including headers) in its raw byte form, which can be useful for processing non-text-based data or for low-level handling of the response.
- Returns:
The raw byte representation of the response.
- Return type:
bytes
- set_content_type_header()¶
Sets the ‘Content-Type’ header based on the current content type.
This method retrieves the content type from the
content_objand sets it as the ‘Content-Type’ header of the response. This informs the client about the type of content being returned (e.g., ‘text/html’, ‘application/json’).… rubric:: Example
If the content type is ‘application/json’, this method will set the header to ‘Content-Type: application/json’.
- set_cookie(key: str, value: str = '', domain: Optional[str] = None, path: str = '/', max_age: Optional[Union[int, datetime.timedelta]] = None, expires: Optional[Union[datetime.datetime, str]] = None, secure: bool = False, httponly: bool = False, samesite: Optional[str] = 'Lax') None¶
Set a custom cookie on the HttpResponse.
- Parameters:
key – The name of the cookie (e.g., ‘csrftoken’).
value – The value of the cookie (e.g., ‘some_random_token’).
domain – The domain to set for the cookie. Defaults to None.
path – The path for the cookie. Defaults to ‘/’ indicating the whole site.
max_age – The maximum age of the cookie in seconds or as a timedelta object.
expires – The expiration date of the cookie. Defaults to None.
secure – Whether the cookie should only be sent over HTTPS connections. Defaults to False.
httponly – Whether the cookie should be inaccessible to JavaScript. Defaults to False.
samesite – The SameSite attribute for the cookie. Default is ‘Lax’. Other possible values are ‘Strict’ or ‘None’.
- Raises:
ValueError – If an invalid value is provided for
samesite.
- set_header(header: str, value: str)¶
Updates/sets a response header.
- set_multiple_cookies(cookies: Dict[str, Dict[str, Any]]) None¶
Sets multiple cookies at once. Each cookie is specified by a dictionary of attributes.
- Parameters:
cookies – A dictionary where the key is the cookie name and the value is another dictionary of cookie attributes.
- property status: tuple[int, str]¶
The status of the response
- Returns:
Status code and status message for response
- Return type:
status (tuple)
- property status_code: int¶
Return status code for the response.
- property status_explanation: str¶
Return the status message explanation for the response.
- property status_message: str¶
Return the status message for the response.
- property title_headers: dict¶
Response headers in title format rather than small cased e.g.
{'Connection': 'close'}rather than{'connection': 'close'}.
- class duck.http.response.ComponentResponse(component: duck.html.components.Component, status_code: int = 200, headers: Optional[Dict[str, str]] = None, content_type: Optional[str] = 'text/html')¶
Bases:
duck.http.response.StreamingHttpResponseHTTP response that streams the rendered output of an HTML component.
- Parameters:
component – The component to be rendered in the response.
status_code – HTTP status code. Defaults to 200.
headers – Response headers. Defaults to empty dict.
content_type – Content-Type header. If not provided, it may be inferred.
- Raises:
ValueError – If the component is None.
TypeError – If the component is not an instance of Component.
Initialization
Initialize a streaming response object.
- Parameters:
stream –
The content to stream. This can either be:
A callable that returns bytes or string, which will be repeatedly called to fetch data (in which case, the chunking is handled by the callable itself).
A file-like object (e.g., an instance of
io.IOBasesuch as a file) that supports reading. When using an IO object, the response will read from the object in chunks.An iterable object which has chunks of data as bytes or a string.
status_code – The HTTP status code (default is 200).
headers – Additional response headers (default is an empty dictionary).
content_type – The MIME type of the content (e.g., ‘application/octet-stream’).
chunk_size – The size of chunks in bytes used for reading from the file-like object. This argument is only relevant when the
streamis an IO object. A larger chunk size generally improves performance by reducing the number of I/O operations but consumes more memory during the process. The default value is 2MB (2 048 000 bytes). Common sizes are between 1 MB (1048576 bytes) and 4 MB (4194304 bytes), but it should be adjusted based on the specific use case and server capabilities. If the content is callable, this argument is ignored, and chunking must be handled by the callable itself.
- async async_iter_content() collections.abc.AsyncGenerator[bytes, None]¶
- iter_content() collections.abc.Generator[bytes, None, None]¶
- class duck.http.response.FileResponse(filepath: str, headers: Dict = {}, status_code: int = 206, content_type: Optional[str] = None, chunk_size: int = 2 * 1024 * 1024, start_pos: int = 0, end_pos: Optional[int] = -1)¶
Bases:
duck.http.response.StreamingRangeHttpResponseClass representing an http file response
Initialization
Initializes a streaming HTTP response for serving a file. Determines whether to stream the file in chunks or as a single response based on its size and ensures appropriate headers and content type are set.
- Parameters:
filepath – The path to the file to be streamed.
headers – Additional HTTP headers to include in the response. Defaults to an empty dictionary.
status_code – The HTTP status code for the response. Defaults to 200 (OK).
content_type – The MIME type of the response content. If not provided, it is inferred from the file’s extension. Defaults to None.
chunk_size – The size of chunks (in bytes) for streaming the file. Defaults to 2 MB (2 * 1024 * 1024 bytes). For files smaller than 5 MB, the entire file will be streamed at once.
start_pos – The starting byte position for the range request. Defaults to 0.
end_pos – The ending byte position for the range request. Defaults to -1, meaning the entire stream is used.
- Raises:
FileNotFoundError – If the specified file does not exist.
ValueError – If the file path is invalid or inaccessible.
… admonition:: Notes
If
content_typeis not provided, it is automatically determined from the file type and updated in the response headers.For files smaller than 5 MB, the file will be streamed as a single response by overriding the
chunk_size.
… rubric:: Example
response = CustomFileStreamer( filepath="/path/to/file.txt", headers={"Content-Disposition": "attachment; filename=file.txt"}, content_type="text/plain", chunk_size=8192, )
- class duck.http.response.HttpBadGatewayResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http bad gateway response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpBadRequestResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http bad request response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpBadRequestSyntaxResponse(content: Optional[Union[str, bytes]] = 'Bad Request Syntax', headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http bad request syntax response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpErrorRequestResponse(content: Optional[Union[str, bytes]] = None, status_code: int = 400, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpResponseClass epresenting an http error response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpForbiddenRequestResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http forbidden request response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpMethodNotAllowedResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http method not allowed response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpNotFoundResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http not found response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpRangeNotSatisfiableResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http range not satisfiable response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpRedirectResponse(location: str, headers: Dict = {}, content_type: Optional[str] = None, permanent: bool = False)¶
Bases:
duck.http.response.HttpResponseClass representing an http redirect response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpRequestTimeoutResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http request timeout response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpResponse(content: Optional[Union[str, bytes]] = None, status_code: int = 200, headers: dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.BaseResponseClass representing an http response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpServerErrorResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http server error response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpSwitchProtocolResponse(upgrade_to: str, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpResponseClass representing an HTTP response for switching protocols (101 Switching Protocols).
Initialization
Initialize an HTTP 101 Switching Protocols response.
- Parameters:
upgrade_to – The protocol to upgrade to (e.g., “h2c” for HTTP/2 cleartext).
headers – Additional headers to include in the response.
content_type – Content-Type header (not usually needed for 101 response).
- class duck.http.response.HttpTooManyRequestsResponse(content: Optional[Union[str, bytes]] = 'Too many requests', headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass to representing an http too many requests response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.HttpUnsupportedVersionResponse(content: Optional[Union[str, bytes]] = None, headers: Dict = {}, content_type: Optional[str] = None)¶
Bases:
duck.http.response.HttpErrorRequestResponseClass representing an http unsupported version response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- class duck.http.response.JsonResponse(content: Optional[Dict[str, str]] = None, status_code: int = 200, headers: Dict = {}, content_type='application/json')¶
Bases:
duck.http.response.HttpResponseClass epresenting an json response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.
- duck.http.response.NEGATIVE_RANGE_PATTERN¶
‘compile(…)’
- duck.http.response.RANGE_HEADER_PATTERN¶
‘compile(…)’
- class duck.http.response.StreamingHttpResponse(stream: duck.http.response.StreamingType, status_code: int = 200, headers: Dict = {}, content_type: Optional[str] = 'application/octet-stream', chunk_size: int = 2 * 1024 * 1024)¶
Bases:
duck.http.response.HttpResponseClass representing an HTTP streaming response.
This class allows for streaming large content, such as files or dynamically generated data, in chunks instead of loading the entire content into memory at once. This is particularly useful for handling large files like videos, audio, or data streams.
Notes:
If a stream provided has a method
close, it will be called after the response has been sent.
Initialization
Initialize a streaming response object.
- Parameters:
stream –
The content to stream. This can either be:
A callable that returns bytes or string, which will be repeatedly called to fetch data (in which case, the chunking is handled by the callable itself).
A file-like object (e.g., an instance of
io.IOBasesuch as a file) that supports reading. When using an IO object, the response will read from the object in chunks.An iterable object which has chunks of data as bytes or a string.
status_code – The HTTP status code (default is 200).
headers – Additional response headers (default is an empty dictionary).
content_type – The MIME type of the content (e.g., ‘application/octet-stream’).
chunk_size – The size of chunks in bytes used for reading from the file-like object. This argument is only relevant when the
streamis an IO object. A larger chunk size generally improves performance by reducing the number of I/O operations but consumes more memory during the process. The default value is 2MB (2 048 000 bytes). Common sizes are between 1 MB (1048576 bytes) and 4 MB (4194304 bytes), but it should be adjusted based on the specific use case and server capabilities. If the content is callable, this argument is ignored, and chunking must be handled by the callable itself.
- __repr__()¶
- async _async_read_from_file(file_obj: io.IOBase, chunk_size: int = 2 * 1024 * 1024) collections.abc.Generator¶
Asynchronous helper method to read the content from a file-like object in chunks.
- Parameters:
file_obj – The asynchronous file-like object to stream content from.
chunk_size – The size of each chunk to stream (default is 8192 bytes).
… admonition:: Notes
This method closes the file-like object after yielding all data.
Yields:
bytes: A chunk of data read from the file-like object.
- _read_from_file(file_obj: io.IOBase, chunk_size: int = 2 * 1024 * 1024) collections.abc.Generator¶
Helper method to read the content from a file-like object in chunks.
- Parameters:
file_obj – The file-like object to stream content from.
chunk_size – The size of each chunk to stream (default is 8192 bytes).
Yields:
bytes: A chunk of data read from the file-like object.
- classmethod async_file_io_stream(filepath: str, chunk_size: int = 2 * 1024 * 1024) duck.utils.fileio.AsyncFileIOStream¶
Creates an asynchronous IOBase-like stream from a file for efficient handling of large files.
This method returns an object that mimics the behavior of an io.IOBase stream. The stream can be used to read file content in chunks, and it supports operations like
seek,tell, andread. This is useful for streaming large files with minimal memory usage.- Parameters:
filepath – The path to the file that should be streamed.
chunk_size – The size of each chunk in bytes. Defaults to 2MB.
- Returns:
A custom stream object that behaves like io.IOBase.
- Return type:
Example:
stream = StreamingHttpResponse.file_io_stream('large_file.txt') response = StreamingHttpResponse(stream)Notes:
The file is opened lazily when the stream is accessed.
The
seekandtellmethods allow for random access to the file.
- async async_iter_content() Awaitable[collections.abc.Iterable[bytes]]¶
Coroutine which returns an iterable (like an asynchronous generator) over the response content.
Ensures that the content provider yields chunks of bytes and not raw bytes or strings directly.
- classmethod file_io_stream(filepath: str, chunk_size: int = 2 * 1024 * 1024) duck.utils.fileio.FileIOStream¶
Creates an IOBase-like stream from a file for efficient handling of large files.
This method returns an object that mimics the behavior of an io.IOBase stream. The stream can be used to read file content in chunks, and it supports operations like
seek,tell, andread. This is useful for streaming large files with minimal memory usage.- Parameters:
filepath – The path to the file that should be streamed.
chunk_size – The size of each chunk in bytes. Defaults to 2MB.
- Returns:
A custom stream object that behaves like io.IOBase.
- Return type:
Example:
stream = StreamingHttpResponse.file_io_stream('large_file.txt') response = StreamingHttpResponse(stream)Notes:
The file is opened lazily when the stream is accessed.
The
seekandtellmethods allow for random access to the file.
- iter_content() collections.abc.Iterable[bytes]¶
Returns an iterable (like a generator) over the response content.
Ensures that the content provider yields chunks of bytes and not raw bytes or strings directly.
- class duck.http.response.StreamingRangeHttpResponse(stream: io.IOBase, status_code: int = 206, headers: Dict = {}, content_type: Optional[str] = 'application/octet-stream', chunk_size: int = 2 * 1024 * 1024, start_pos: int = 0, end_pos: Optional[int] = -1)¶
Bases:
duck.http.response.StreamingHttpResponseA subclass of StreamingHttpResponse designed to handle HTTP responses that support partial content (range requests), allowing clients to request specific byte ranges of the response content. This is useful for handling large files and enabling features like resuming downloads or streaming media.
Example:
response = StreamingRangeHttpResponse( stream=my_file, start_pos=-1000, # Last 1000 bytes chunk_size=1024, ) return responseInitialization
Initialize StreamingRangeHttpResponse class.
- Parameters:
stream – The stream from which to read the response data. It can be a file-like object or an in-memory stream.
status_code – The HTTP status code to return. Defaults to 206 (Partial Content).
headers – Additional HTTP headers to include in the response. Defaults to an empty dict.
content_type – The MIME type of the response content. Defaults to ‘application/octet-stream’.
chunk_size – The number of bytes to send in each chunk. Defaults to 2MB (2 * 1024 * 1024 bytes).
start_pos – The starting byte position for the range request. Defaults to 0, can also be a negative.
end_pos – The ending byte position for the range request. Defaults to -1, meaning the entire stream is used.
- __repr__()¶
- async _async_get_range_stream() collections.abc.AsyncGenerator¶
Asynchronous generator that yields chunks of the stream, starting from start_pos and ending at end_pos. The stream will be read in chunks defined by
chunk_size.
- _get_range_stream() collections.abc.Generator¶
Generator that yields chunks of the stream, starting from start_pos and ending at end_pos. The stream will be read in chunks defined by
chunk_size.
- clear_content_range_headers()¶
Clear or deletes the content range headers.
- classmethod extract_range(range_header: str) Optional[Tuple[int, int]]¶
Extracts the byte range from the ‘Range’ header in the response and validates the range.
- Parameters:
range_header – The HTTP response ‘Range’ header.
- Returns:
A tuple of the form (start, end) representing the byte range, or None if no range is specified.
- Return type:
Tuple[int, int] or None
- Raises:
ValueError – If the ‘Range’ header format is invalid or if the extracted range is invalid (e.g.,
start_pos > end_pos).
- parse_range(start_pos: int, end_pos: int) int¶
Parses content range and sets the respective content range headers.
- Returns:
The stream size or length.
- Return type:
int
- set_content_range_headers()¶
Sets the content range headers based on current content range.
- validate_stream(stream)¶
Validates that the given stream has the necessary methods and ensures coroutine compatibility in async context.
- Raises:
ValueError – If a required method is missing.
AsyncViolationError – If a required method is not asynchronous in async context.
- duck.http.response.StreamingType¶
None
- class duck.http.response.TemplateResponse(request: duck.http.request.HttpRequest, template: str, context: Dict = {}, status_code: int = 200, headers: Dict = {}, content_type: str = 'text/html', engine: Optional[duck.template.environment.Engine] = None)¶
Bases:
duck.http.response.HttpResponseTemplateResponse class representing an http template response.
Initialization
’ Initialize Response object
- Parameters:
payload_obj – Response Header object to represent Header
content_obj – Content object.