duck.shortcuts

This module provides various utility functions and shortcuts for handling common operations in the Duck framework.

It includes functions for rendering templates, generating responses, resolving URLs, managing CSRF tokens, handling static and media resources, and manipulating HTTP responses.

The module also defines URLResolveError, an exception raised when URL resolution fails.

Package Contents

Functions

async_render

Asynchronously renders a template and returns the response.

content_replace

Replaces response content with new content.

csrf_token

Returns the csrf token, whether for django or duck request.

django_render

Render a Django template.

jinja2_render

Render a jinja2 template.

jsonify

Returns a JsonResponse object

media

Returns the absolute media URL path for provided resource.

merge

This merges two http response objects into one http response object

not_found404

Returns a 404 error response, either a simple response or a template response given DEBUG mode is on or off.

redirect

Returns a HttpRedirectResponse object

render

Renders a template and returns the response.

replace_response

Replaces/transforms the old response into a new response object (inplace).

resolve

This resolves a URL based on name.

static

Returns the absolute static url path for provided resource.

streaming_content_replace

Replaces response content with new content.

to_response

Converts any value to http response (including html components).

Data

__all__

API

exception duck.shortcuts.URLResolveError

Bases: Exception

Raised if URL resolving fails.

Initialization

Initialize self. See help(type(self)) for accurate signature.

duck.shortcuts.__all__

[‘simple_response’, ‘template_response’, ‘URLResolveError’, ‘jinja2_render’, ‘django_render’, ‘rende…

async duck.shortcuts.async_render(request, template: str, context: Dict[Any, Any] = {}, status_code: int = 200, engine: str = 'django', **kw) duck.http.response.TemplateResponse

Asynchronously renders a template and returns the response.

Parameters:
  • request – Http request object.

  • template – Template path within global or blueprint template dirs.

  • context – Dictionary respresenting template context.

  • status_code – The response status code, defaults to 200.

  • engine – Template engine to use for rendering template, defaults to ‘django’.

  • **kw – Additional keywords to parse to the http response for the current template engine.

Returns:

Http response rendered using Django or Jinja2.

Return type:

TemplateResponse

duck.shortcuts.content_replace(response: duck.http.response.HttpResponse, new_data: Union[bytes, str], new_content_type: str = 'auto', new_content_filepath: str = 'use_existing')

Replaces response content with new content.

Parameters:
  • response – Response to replace content for.

  • new_data – String or bytes to set for content.

  • new_content_type – The new content type, Defaults to auto to automatically determine the content type.

  • new_content_filepath – Filepath to the content, Defaults to “use_existing” to use the already set filepath.

duck.shortcuts.csrf_token(request) str

Returns the csrf token, whether for django or duck request.

duck.shortcuts.django_render(request: duck.http.request.HttpRequest, template: str, context: Dict[Any, Any] = {}, status_code: int = 200, **kw) duck.http.response.TemplateResponse

Render a Django template.

Parameters:
  • request – The request object.

  • template – The Django template within the global or blueprint template dirs.

  • context – The context dictionary to pass to the template. Defaults to an empty dictionary.

  • status_code – The response status code, defaults to 200.

  • **kw – Additional keyword arguments to parse to the TemplateResponse.

Returns:

The response object with the rendered Django template.

Return type:

TemplateResponse

duck.shortcuts.jinja2_render(request: duck.http.request.HttpRequest, template: str, context: Dict[Any, Any] = {}, status_code: int = 200, **kw) duck.http.response.TemplateResponse

Render a jinja2 template.

Parameters:
  • request – The request object.

  • template – The Jinja2 template with global or blueprint template dirs.

  • context – The context dictionary to pass to the template. Defaults to an empty dictionary.

  • status_code – The response status code, defaults to 200.

  • **kw – Additional keyword arguments to parse to TemplateResponse.

Returns:

The response object with the rendered content.

Return type:

TemplateResponse

duck.shortcuts.jsonify(data: Any, status_code: int = 200, **kw)

Returns a JsonResponse object

Parameters:
  • data – Json serializable data

  • status_code – The response status code. Defaults to 200.

  • **kwargs – Extra keywords to parse to JsonResponse

Returns:

The http json response object.

Return type:

JsonResponse

duck.shortcuts.media(resource_path: str) str

Returns the absolute media URL path for provided resource.

duck.shortcuts.merge(base_response: duck.http.response.HttpResponse, take_response: duck.http.response.HttpResponse, merge_headers: bool = False) duck.http.response.HttpResponse

This merges two http response objects into one http response object

Notes:

  • By default, this only merge content and content headers.

  • This is useful especially when you have a certain type of HttpResponse (for instance HttpNotFoundResponse) but you want that Base response object to have content of a rendered html file.

duck.shortcuts.not_found404(request: Optional[duck.http.request.HttpRequest] = None, body: str = None) duck.http.response.HttpResponse

Returns a 404 error response, either a simple response or a template response given DEBUG mode is on or off.

Parameters:
  • request – The target http request.

  • body – Body for the 404 response.

Returns:

The http not found response object.

Return type:

HttpResponse

duck.shortcuts.redirect(location: str, permanent: bool = False, content_type='text/html', **kw)

Returns a HttpRedirectResponse object

Parameters:
  • location – URL location

  • permanent – Whether this is a permanent redirect, defaults to False

  • content_type – Content type for response, defaults to ‘text/html’

  • **kw – Keyword arguments to parse to HttpRedirectResponse

Returns:

The http redirect response object.

Return type:

HttpRedirectResponse

duck.shortcuts.render(request, template: str, context: Dict[Any, Any] = {}, status_code: int = 200, engine: str = 'django', **kw) duck.http.response.TemplateResponse

Renders a template and returns the response.

Parameters:
  • request – Http request object.

  • template – Template path within the TEMPLATE_DIR.

  • context – Dictionary respresenting template context.

  • status_code – The response status code, defaults to 200.

  • engine – Template engine to use for rendering template, defaults to ‘django’.

  • **kw – Additional keywords to parse to the http response for the current template engine.

Returns:

Http response rendered using Django or Jinja2.

Return type:

TemplateResponse

duck.shortcuts.replace_response(old_response: duck.http.response.HttpResponse, new_response: duck.http.response.HttpResponse, full_replacement: bool = True) duck.http.response.HttpResponse

Replaces/transforms the old response into a new response object (inplace).

Parameters:
  • old_response – The response you want to apply modifications to.

  • new_response – The base response you want to get values or reference data from.

  • full_replacement – Whether to completely alter the old response into identical response with the new response (defaults to True). As the name suggests, this replaces all attributes of old with new ones and even the response type will become the same as the new one’s. If set to False, the old response will keep its attributes but status, headers & content will change. This might not work if responses includes unmatching __slots__ attributes.

Returns:

The old response but transformed or combined with new response

Return type:

HttpResponse

duck.shortcuts.resolve(name: str, absolute: bool = True, fallback_url: Optional[str] = None) str

This resolves a URL based on name.

Parameters:
  • name – The name of the URL to resolve.

  • absolute – This will return the absolute url instead of registered path only but it requires the app to be in running state

  • fallback_url – The fallback url to use if the URL is not found.

Important

This function is primarily designed for resolving URLs registered as plain, static paths.

It is strongly recommended to use this function only with URLs registered in the form: pattern = '/url/path'

Using this function with dynamic URLs (e.g., those containing path parameters or regular expression patterns) will return the raw, unregistered pattern, which is typically not useful for direct use.

For example, using it with: pattern = '/url/<some_input>/path'  pattern = '/url/hello*'

will return those patterns as is, and not a resolved URL.

Raises:

(URLResolveError) – Raised if there is no url associated with the name, url associated with the name is not a plain url

duck.shortcuts.static(resource_path: str) str

Returns the absolute static url path for provided resource.

duck.shortcuts.streaming_content_replace(response: duck.http.response.StreamingHttpResponse, stream: Union[Callable, collections.abc.Iterable[bytes]], chunk_size: int = 2 * 1024 * 1024) None

Replaces response content with new content.

Parameters:
  • response – Streaming Http Response to replace content for.

  • stream – The new stream.

  • chunk_size – The new chunk size.

Notes:

  • This approach only replace content, it doesn’t touch any headers.

duck.shortcuts.to_response(value: Any, **kwargs) Union[duck.http.response.BaseResponse, duck.http.response.HttpResponse]

Converts any value to http response (including html components).

Parameters:
  • value – The target object to convert/transform.

  • **kwargs – The keyword arguments to parse to the HTTP response instance.

Raises:

TypeError – If the value is not convertable to http response.

Notes:

  • If value is already a response object, nothing will be done.