duck.http.request

Module containing Request class which represents an http request.

Note

If you run into errors or unexpected behavior when interacting with a request, be sure to inspect the Request.error attribute for diagnostic information.

Module Contents

Classes

Request

An object representing an HTTP request, including method, headers, and body data.

Data

HttpRequest

SUPPORTED_HTTP_VERSIONS

API

duck.http.request.HttpRequest

None

class duck.http.request.Request(**kwargs)

An object representing an HTTP request, including method, headers, and body data.

Notes:

  • If you run into errors or unexpected behavior when interacting with a request, be sure to inspect the Request.error attribute for diagnostic information.

  • The recommended method for parsing raw request data is to use parse.

Initialization

Initializes a request object, populating fields based on available data.

Parameters:
  • method – The HTTP method (e.g., ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’).

  • path – The request path (excluding domain and query string).

  • http_version – The HTTP version (e.g., ‘HTTP/1.1’, ‘HTTP/2’).

  • headers – Request headers in lowercase key-value pairs.

  • error – An optional exception raised during parsing.

  • protocol – The protocol used (typically ‘HTTP’).

  • content_obj – Optional content object.

… admonition:: Notes

  • To extract information like request port, the ‘Host’ header must be present.

  • This class aims to encapsulate request details for further processing.

  • Use method ‘parse_raw_request’ to populate request using raw data.

  • The application attribute will be set by WSGI creating request

  • The SESSION attribute is an instance of SessionStore

  • The QUERY attribute is an instance of QueryDict which contains ‘CONTENT_QUERY’ and ‘URL_QUERY’

  • These two keys contains both content queries and url queries respectively

property ID

Retrieves the 8-bit unique identifier for the request.

If the ID has not been generated yet, it will be created using a hash of a random number. The ID is represented as a substring of the MD5 hash, limited to the first 8 characters.

Returns:

The 8-character unique identifier for the request.

Return type:

str

property META: dict

Retrieves the metadata associated with the request.

This property calls the build_meta method to ensure the request’s metadata is up-to-date and then returns the stored metadata dictionary.

Returns:

A dictionary containing the metadata of the request.

Return type:

dict

Notes:

  • The build_meta method is called each time this property is accessed to ensure the metadata is fresh.

property SESSION

Retrieves the session associated with the request.

This property returns the internal session object, which is typically used for tracking and managing the state of a user’s session throughout the lifecycle of a request.

Returns:

The session object associated with the request.

Return type:

Any

SUPPORTED_HTTP_VERSIONS: list

None

List of all supported http versions e.g HTTP/1.1.

Important

This is case-sensitive, only caps are allowed.

__repr__()
_build_headers() bytes

Construct headers for the request

_build_request_line() bytes

Construct the request line (method, path, HTTP version)

_extract_and_process_request_data()

Extracts and processes session, authentication, URL queries, and content queries from the incoming request and updates the global QueryDict.

This method handles:

  • Extracting cookies and authentication data from the request.

  • Extracting URL and content-related query parameters.

  • Updating the global QUERY dictionary with extracted values.

  • Combining the URL and content queries into a single query and attaching it to the request method as a QueryDict.

Updates:

  • self.COOKIES: Extracted cookies from the request.

  • self.AUTH: Extracted authentication data from the request.

  • self.QUERY: Updated global QueryDict with URL and content query data.

  • self.method.upper(): A QueryDict containing the combined URL and content queries.

_parse_content(raw_content: bytes)
    Parses the raw content from a request and sets it as the instance content.

    This method processes the raw content passed as bytes, strips any leading and
    trailing carriage returns or newlines (`

), and sets it as the content of         the request. It does so by calling the set_content` method, with an option to avoid adding content-related headers automatically.

    Args:
        raw_content (bytes): The raw content in byte format that was sent with the
                              request. It may represent the body of a POST or PUT
                              request, or any data transmitted after the headers.

    Notes:
        - This method assumes the content is properly formatted in the request.
        - The left stripping of `

ensures that no unnecessary line breaks remain before               storing the content.             - The method does not automatically add content-related headers (e.g.,              Content-Length) by setting auto_add_content_headers=Falsein the call to              set_content`.

_parse_raw_headers(raw_headers: bytes)

Parses raw HTTP headers from bytes into structured attributes.

This method processes the raw HTTP request headers (excluding content) passed as bytes, and sets relevant instance attributes such as the HTTP method, full path, HTTP version, and individual headers.

It performs the following tasks:

  • Decodes and extracts the HTTP method, path, and version from the top header.

  • Decodes each header line, validates its format, and assigns them to instance headers.

  • Ensures that the HTTP version is supported by the server.

Parameters:

raw_headers – The raw HTTP headers in byte format, typically received from a client request. The first line contains the HTTP method, path, and version, followed by headers.

Raises:
_parse_raw_request(raw_request: bytes)

Parses a raw HTTP request in byte format into its components, including headers and body.

This method is responsible for taking a raw HTTP request (as bytes) and splitting it into its respective parts: headers, content, and other request data. It then processes each part, including parsing the headers, parsing the content, and extracting necessary data (such as cookies, authentication, and query parameters).

Parameters:

raw_request – The raw HTTP request data in byte format, typically received from a client. This includes the HTTP method, path, headers, and body/content.

Raises:

RequestSyntaxError – If the request has an invalid format or contains errors.

Updates: - self.COOKIES: Extracted cookies from the request. - self.AUTH: Extracted authentication data from the request. - self.QUERY: Updated global QueryDict with URL and content query data. - self.method.upper(): A QueryDict containing the combined URL and content queries.

_parse_request(topheader: str, headers: Dict[str, str], content: bytes)

Parses a HTTP request into its components, including headers and body.

Raises:

Updates: - self.COOKIES: Extracted cookies from the request. - self.AUTH: Extracted authentication data from the request. - self.QUERY: Updated global QueryDict with URL and content query data. - self.method.upper(): A QueryDict containing the combined URL and content queries.

_set_auth_headers()

Sets Authorization and Proxy-Authorization headers if not already present.

property absolute_uri: str

Resolves the absolute URI for the current request.

This property constructs the absolute URI by combining the base URL and the request path. The absolute URI includes the full protocol, domain, and path to the requested resource.

Returns:

The absolute URI of the request, including scheme and domain.

Return type:

str

property absolute_ws_uri: str

Resolves the absolute WebSocket URI for the current request.

This property constructs the absolute URI by combining the base URL and the request path. The absolute URI includes the full protocol, domain, and path to the requested resource.

Returns:

The absolute URI of the request, including scheme and domain.

Return type:

str

static add_queries_to_url(url: str, queries: Dict) str

This adds queries to a URL.

build_absolute_uri(path: str = None) str

Constructs an absolute URL by combining the scheme, netloc, and the provided path.

This method ensures that the resulting URL includes the scheme, host, and port (if applicable). It relies on the scheme and port attributes for accurate URL construction.

Parameters:

path – The URL path to append to the base URL. Defaults to None.

Returns:

A fully constructed absolute URL.

Return type:

str

build_absolute_ws_uri(path: str = None) str

Constructs an absolute WebSocket URL by combining the scheme, netloc, and the provided path.

This method ensures that the resulting URL includes the scheme, host, and port (if applicable). It relies on the scheme and port attributes for accurate URL construction.

Parameters:

path – The URL path to append to the base URL. Defaults to None.

Returns:

A fully constructed absolute URL.

Return type:

str

build_meta() Dict

Builds and returns the metadata associated with the request.

This method collects relevant information about the current request and compiles it into a dictionary. The metadata can include details such as headers, request method, URI, and other contextual data that may be useful for logging, debugging, or request processing.

Returns:

A dictionary containing metadata about the request.

Return type:

Dict

… admonition:: Notes

  • The specific metadata included in the dictionary depends on the implementation and purpose of the request.

property connection: str

Retrieves the connection mode for the request.

This property returns the value of the Connection header from the request, or defaults to 'close' if the header is not set.

Returns:

The connection mode for the request. Defaults to 'close' if not set.

Return type:

str

… admonition:: Notes

  • The Connection header controls whether the network connection should be kept alive or closed after the request is completed.

property content

Retrieves the content data associated with the request.

Returns:

The data of the content associated with the request, typically the payload.

Return type:

Any

property domain: str

Returns the hostname within the Host header.

static extract_auth_from_request(request) Dict[str, str]

Extracts authentication-related information from the request headers.

This method looks for both the Authorization and Proxy-Authorization headers and returns a dictionary containing the values if they exist.

Parameters:

request – The request object containing the headers to extract from.

Returns:

A dictionary with keys ‘auth’ and ‘proxy_auth’, containing the corresponding header values if present. If neither header is found, an empty dictionary is returned.

Return type:

Dict[str, str]

Example:

request = SomeRequestObject()
auth_data = extract_auth_from_request(request)
print(auth_data)  # Outputs {'auth': 'Bearer token_value', 'proxy_auth': 'Basic proxy_token'}
static extract_content_queries(request) duck.http.querydict.QueryDict

Extract query parameters and file uploads from the request content.

This method retrieves all query parameters from the request body, including files and form data. However, uploaded files are not automatically saved—you must manually call save() on request.FILES[query_key] where necessary.

Parameters:

request – The incoming HTTP request object.

Returns:

A dictionary-like object containing extracted query parameters and file data from the request.

Return type:

QueryDict

static extract_cookies_from_request(request) Dict[str, str]

Extracts and returns the cookies from the given request.

This static method extracts cookies from the request object and returns them as a dictionary, where each key is a cookie name and the corresponding value is the cookie’s value.

Parameters:

request – The request object from which to extract cookies.

Returns:

A dictionary containing the cookies extracted from the request, with cookie names as keys and cookie values as values.

Return type:

Dict[str, str]

… admonition:: Notes

  • The request must have a way of storing cookies (e.g., in a cookies attribute or method).

static extract_url_queries(url: str) Tuple[str, duck.http.querydict.QueryDict]

Extracts the query parameters from a given URL.

This method splits the provided URL into two parts: - The base URL (without the query string). - A QueryDict containing the parsed query parameters.

Parameters:

url – The URL containing the query string (e.g., /path/?query1=value1&query2=value2).

Returns:

A tuple where the first element is the base URL (without the query string) and the second element is a QueryDict containing the query parameters.

Return type:

Tuple[str, QueryDict]

… admonition:: Notes

  • The QueryDict object is a specialized dictionary that can handle multiple values for the same query key.

  • If the URL does not contain query parameters, the second element of the returned tuple will be an empty QueryDict.

… rubric:: Example

url = “/path/?query1=value1&query2=value2” base_url, queries = extract_url_queries(url) print(base_url) # “/path/” print(queries) # {“query1”: [“value1”], “query2”: [“value2”]}

property fullpath

Retrieves the full path of the request, including query parameters.

This includes both the path and any query strings, for example: /home?q=12&w=4.

Returns:

The full path of the request.

Return type:

str

get_header(header: str, default_value: Optional[str] = None) Optional[str]

Retrieves the value of a specified header.

This method looks up the given header in the request and returns its value. If the header is not found, it returns the specified default_value (or None if no default is provided).

Parameters:
  • header – The name of the header to retrieve.

  • default_value – The value to return if the header is not found. Defaults to None.

Returns:

The value of the header if it exists, otherwise the default_value.

Return type:

Optional[str]

… admonition:: Notes

  • If the header does not exist and no default_value is provided, None will be returned.

property has_error: bool

Returns boolean on whether boolean has an error.

property headers: dict

Retrieves the headers of the request.

This property returns the request headers as a dictionary with all header names in lowercase.

Returns:

The headers of the request, represented as a dictionary where all header names are in lowercase.

Return type:

dict

property host: str

Returns the value of the Host header in the request.

If the Host header is not set, raises a RequestHostError.

Returns:

The value of the Host header.

Return type:

str

Raises:

RequestHostError – If the Host header is not set in the request.

property hostname: str

Returns the hostname within the Host header.

property json

Retrieves the json from the request content.

Returns:

The data of the content associated with the request, typically the payload.

Return type:

dict

Raises:

ValueError – If the request body cannot be parsed as JSON.

property origin: Optional[str]

Retrieves the ‘Origin’ header from the HTTP request.

The ‘Origin’ header indicates the origin (protocol, host, and port) of the request. It is typically used in cross-origin requests to specify the origin making the request.

Returns:

The value of the ‘Origin’ header, or None if the header is not set.

Return type:

Optional[str]

parse(request_data: duck.http.request_data.RequestData)

Parses request data to the request object

parse_raw_request(raw_request: bytes)

Parse raw request in bytes. If error occurs during parsing, it will be recorded.

This method attempts to parse a raw HTTP request in byte format. If any error occurs during the parsing process, the error is captured and stored in the error attribute.

Parameters:

raw_request – The raw HTTP request in byte format.

Sets:

  • self.error (Optional[Exception]): If an error occurs during parsing, it is stored here.

parse_request(topheader: str, headers: Dict[str, str], content: bytes)

Parse request from topheader, headers and content

Parameters:
  • topheader – The request line or topheader containing method, path and http version

  • headers – The request headers

  • content – The request body or content

Sets: Optional[Exception]): If an error occurs during parsing, it is stored here.

property path: Optional[str]

Retrieves the path portion of the request URL.

This property returns the URL path without any query parameters, representing the main part of the request URL.

Returns:

The path of the request, or None if not set.

Return type:

Optional[str]

property port: Optional[int]

Returns the port as integer within the Host header.

Returns:

If port exists within the Host header else None

Return type:

Optional[int]

property protocol: Optional[str]

Retrieves the HTTP version used in the request.

This returns the protocol version specified in the request, typically in the format of ‘HTTP/1.1’ or ‘HTTP/2’. If the protocol is not defined, it returns None.

Returns:

The HTTP protocol version, or None if not set.

Return type:

Optional[str]

property raw: bytes

Construct raw request from this Request object.

property referer: Optional[str]

Retrieves the ‘Referer’ header from the HTTP request.

The ‘Referer’ header indicates the address of the previous web page from which a link to the currently requested page was followed.

Returns:

The value of the ‘Referer’ header, or None if the header is not set.

Return type:

Optional[str]

property remote_addr: Tuple[str, int]

Returns the client remote address and port.

property scheme: str

Retrieves the scheme (protocol) of the HTTP request.

The scheme is typically ‘http’ or ‘https’, indicating the protocol used for the request. This method returns ‘https’ if the request uses HTTPS, otherwise it returns ‘http’.

Returns:

The scheme (either ‘http’ or ‘https’) for the request.

Return type:

str

property session

Alias for the SESSION property.

This provides the same value as request.SESSION, allowing an alternative way to access the session object.

Returns:

The session object associated with the request.

Return type:

Any

set_connection(mode: str)

Sets the request connection mode by modifying the connection header.

set_content(data: bytes, auto_add_content_headers: bool = True)

Sets the content of the request. This also sets the appropriate content headers if auto_add_content_headers=True

Parameters:
  • data – Data in bytes to set as content

  • auto_add_content_headers – Sets appropriate content headers like Encoding, Content-Length and Content-Type

set_header(header: str, value: str)

Adds or replaces a header in the request.

This method ensures that all header names are stored in lowercase within self.headers for consistency and proper handling of headers, as HTTP header names are case-insensitive.

Parameters:
  • header – The name of the header to add or replace.

  • value – The value to set for the specified header.

… admonition:: Notes

  • If the header already exists, its value will be replaced with the new value.

  • The header name will be automatically converted to lowercase before being stored.

property title_headers: dict

Request headers in title format rather than small cased e.g. {‘Connection’: ‘close’} rather than {‘connection’: ‘close’}

property uses_https

Whether the request is on HTTP or HTTPS protocol, this is determined by checking if application is started with https enabled or not.

property version_number: Optional[str]

Get the version number of the request as a string.

Notes: This is very different from attr http_version as it only includes version number as a string

duck.http.request.SUPPORTED_HTTP_VERSIONS

[‘HTTP/1.0’, ‘HTTP/1.1’]