cowbird.api.exception

Attributes

JSON

ParamsType

CONTENT_TYPE_ANY

CONTENT_TYPE_APP_XML

CONTENT_TYPE_HTML

CONTENT_TYPE_JSON

CONTENT_TYPE_PLAIN

CONTENT_TYPE_TXT_XML

SUPPORTED_ACCEPT_TYPES

LOGGER

RAISE_RECURSIVE_SAFEGUARD_MAX

RAISE_RECURSIVE_SAFEGUARD_COUNT

PARAM_REGEX

EMAIL_REGEX

UUID_REGEX

URL_REGEX

INDEX_REGEX

Functions

get_logger(→ logging.Logger)

Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when

islambda(→ bool)

Evaluate if argument is a callable lambda expression.

verify_param(→ None)

Evaluate various parameter combinations given the requested verification flags. Given a failing verification,

apply_param_content(→ cowbird.typedefs.JSON)

Formats and applies the failing parameter conditions and results to returned JSON content according to flags.

evaluate_call(→ Any)

Evaluates the specified call with a wrapped HTTP exception handling. On failure, tries to call.

valid_http(...)

Returns successful HTTP with standardized information formatted with content type. (see raise_http() for HTTP

raise_http(…)

Raises error HTTP with standardized information formatted with content type.

validate_params(→ Tuple[int, str, cowbird.typedefs.JSON])

Validates parameter types and formats required by valid_http() and raise_http().

format_content_json_str(→ str)

Inserts the code, details, content and type within the body using json format. Includes also any other specified

rewrite_content_type(→ Tuple[str, ...)

Attempts to rewrite the type field inserted by various functions such as:

generate_response_http_format(...)

Formats the HTTP response content according to desired content_type using provided HTTP code and content.

Module Contents

cowbird.api.exception.JSON[source]
cowbird.api.exception.ParamsType[source]
cowbird.api.exception.CONTENT_TYPE_ANY = '*/*'[source]
cowbird.api.exception.CONTENT_TYPE_APP_XML = 'application/xml'[source]
cowbird.api.exception.CONTENT_TYPE_HTML = 'text/html'[source]
cowbird.api.exception.CONTENT_TYPE_JSON = 'application/json'[source]
cowbird.api.exception.CONTENT_TYPE_PLAIN = 'text/plain'[source]
cowbird.api.exception.CONTENT_TYPE_TXT_XML = 'text/xml'[source]
cowbird.api.exception.SUPPORTED_ACCEPT_TYPES[source]
cowbird.api.exception.get_logger(name: str, level: int | None = None, force_stdout: bool = None, message_format: str | None = None, datetime_format: str | None = None) logging.Logger[source]

Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when level is logging.NOTSET.

cowbird.api.exception.islambda(func: Any) bool[source]

Evaluate if argument is a callable lambda expression.

cowbird.api.exception.LOGGER[source]
cowbird.api.exception.RAISE_RECURSIVE_SAFEGUARD_MAX = 5[source]
cowbird.api.exception.RAISE_RECURSIVE_SAFEGUARD_COUNT = 0[source]
cowbird.api.exception.PARAM_REGEX = '^[A-Za-z0-9]+(?:[\\s_\\-\\.][A-Za-z0-9]+)*$'[source]
cowbird.api.exception.EMAIL_REGEX[source]
cowbird.api.exception.UUID_REGEX[source]
cowbird.api.exception.URL_REGEX[source]
cowbird.api.exception.INDEX_REGEX = '^[0-9]+$'[source]
cowbird.api.exception.verify_param(param: Any, param_compare: Any | List[Any] | Type[Any] | List[Type[Any]] | None = None, param_name: str | None = None, param_content: cowbird.typedefs.JSON | None = None, with_param: bool = True, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPBadRequest, http_kwargs: cowbird.typedefs.ParamsType | None = None, msg_on_fail: str = '', content: cowbird.typedefs.JSON | None = None, content_type: str = CONTENT_TYPE_JSON, not_none: bool = False, not_empty: bool = False, not_in: bool = False, not_equal: bool = False, is_true: bool = False, is_false: bool = False, is_none: bool = False, is_empty: bool = False, is_in: bool = False, is_equal: bool = False, is_type: bool = False, matches: bool = False) None[source]

Evaluate various parameter combinations given the requested verification flags. Given a failing verification, directly raises the specified http_error. Invalid usage exceptions generated by this verification process are treated as HTTPInternalServerError. Exceptions are generated using the standard output method.

Parameters:
  • param – parameter value to evaluate

  • param_compare – Other value(s) to test param against. Can be an iterable (single value resolved as iterable unless None). To test for None type, use is_none/not_none flags instead.

  • param_name – name of the tested parameter returned in response if specified for debugging purposes

  • param_content – Additional JSON content to apply to generated error content on raise when with_param is True. Must be JSON serializable. Provided content can override generated error parameter if matching fields.

  • with_param – On raise, adds values of param, param_name and param_compare, as well as additional failing conditions metadata to the JSON response body for each of the corresponding value.

  • http_error – derived exception to raise on test failure (default: HTTPBadRequest)

  • http_kwargs – additional keyword arguments to pass to http_error called in case of HTTP exception

  • msg_on_fail – message details to return in HTTP exception if flag condition failed

  • content – json formatted additional content to provide in case of exception

  • content_type – format in which to return the exception (one of cowbird.common.SUPPORTED_ACCEPT_TYPES)

  • not_none – test that param is not None type

  • not_empty – test that param is not an empty iterable (string, list, set, etc.)

  • not_in – test that param does not exist in param_compare values

  • not_equal – test that param is not equal to param_compare value

  • is_true – test that param is True

  • is_false – test that param is False

  • is_none – test that param is None type

  • is_empty – test param for an empty iterable (string, list, set, etc.)

  • is_in – test that param exists in param_compare values

  • is_equal – test that param equals param_compare value

  • is_type – test that param is of same type as specified by param_compare type

  • matches – test that param matches the regex specified by param_compare value

Raises:
  • HTTPError – if tests fail, specified exception is raised (default: HTTPBadRequest)

  • HTTPInternalServerError – for evaluation error

Returns:

nothing if all tests passed

cowbird.api.exception.apply_param_content(content: cowbird.typedefs.JSON, param: Any, param_compare: Any, param_name: str, with_param: bool, param_content: cowbird.typedefs.JSON | None, needs_compare: bool, needs_iterable: bool, is_type: bool, fail_conditions: cowbird.typedefs.JSON) cowbird.typedefs.JSON[source]

Formats and applies the failing parameter conditions and results to returned JSON content according to flags.

See also

verify_param()

cowbird.api.exception.evaluate_call(call: Callable[[], Any], fallback: Callable[[], None] | None = None, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: cowbird.typedefs.ParamsType | None = None, msg_on_fail: str = '', content: cowbird.typedefs.JSON | None = None, content_type: str = CONTENT_TYPE_JSON) Any[source]

Evaluates the specified call with a wrapped HTTP exception handling. On failure, tries to call.

fallback if specified, and finally raises the specified http_error.

Any potential error generated by fallback or http_error themselves are treated as HTTPInternalServerError.

Exceptions are generated using the standard output method formatted based on specified content_type.

Example:

normal call:

try:
    res = func(args)
except Exception as exc:
    fb_func()
    raise HTTPExcept(exc.message)

wrapped call:

res = evaluate_call(lambda: func(args), fallback=lambda: fb_func(), http_error=HTTPExcept, **kwargs)
Parameters:
  • call – function to call, MUST be specified as lambda: <function_call>

  • fallback – function to call (if any) when call failed, MUST be lambda: <function_call>

  • http_error – alternative exception to raise on call failure

  • http_kwargs – additional keyword arguments to pass to http_error if called in case of HTTP exception

  • msg_on_fail – message details to return in HTTP exception if call failed

  • content – json formatted additional content to provide in case of exception

  • content_type – format in which to return the exception (one of cowbird.common.SUPPORTED_ACCEPT_TYPES)

Raises:
  • http_error – on call failure

  • HTTPInternalServerError – on fallback failure

Returns:

whichever return value call might have if no exception occurred

cowbird.api.exception.valid_http(http_success: Type[pyramid.httpexceptions.HTTPSuccessful] | Type[pyramid.httpexceptions.HTTPRedirection] = HTTPOk, http_kwargs: cowbird.typedefs.ParamsType | None = None, detail: str | None = '', content: cowbird.typedefs.JSON | None = None, content_type: str | None = CONTENT_TYPE_JSON) pyramid.httpexceptions.HTTPSuccessful | pyramid.httpexceptions.HTTPRedirection[source]

Returns successful HTTP with standardized information formatted with content type. (see raise_http() for HTTP error calls)

Parameters:
  • http_success – any derived class from valid HTTP codes (<400) (default: HTTPOk)

  • http_kwargs – additional keyword arguments to pass to http_success when called

  • detail – additional message information (default: empty)

  • content – json formatted content to include

  • content_type – format in which to return the exception (one of cowbird.utils.SUPPORTED_ACCEPT_TYPES)

Returns:

formatted successful response with additional details and HTTP code

cowbird.api.exception.raise_http(http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: cowbird.typedefs.ParamsType | None = None, detail: str = '', content: cowbird.typedefs.JSON | None = None, content_type: str = CONTENT_TYPE_JSON, nothrow: Literal[False] = False) NoReturn[source]
cowbird.api.exception.raise_http(http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: cowbird.typedefs.ParamsType | None = None, detail: str = '', content: cowbird.typedefs.JSON | None = None, content_type: str = CONTENT_TYPE_JSON, nothrow: Literal[True] = False) pyramid.httpexceptions.HTTPException

Raises error HTTP with standardized information formatted with content type.

The content contains the corresponding http error code, the provided message as detail and optional specified additional json content (kwarg dict).

See also

valid_http() for HTTP successful calls

Parameters:
  • http_error – any derived class from base HTTPError (default: HTTPInternalServerError)

  • http_kwargs – additional keyword arguments to pass to http_error if called in case of HTTP exception

  • detail – additional message information (default: empty)

  • content – json formatted content to include

  • content_type – format in which to return the exception (one of cowbird.utils.SUPPORTED_ACCEPT_TYPES)

  • nothrow – returns the error response instead of raising it automatically, but still handles execution errors

Raises:

HTTPError – formatted raised exception with additional details and HTTP code

Returns:

HTTPError formatted exception with additional details and HTTP code only if nothrow is True

cowbird.api.exception.validate_params(http_class: Type[pyramid.httpexceptions.HTTPException], http_base: Type[pyramid.httpexceptions.HTTPException] | Iterable[Type[pyramid.httpexceptions.HTTPException]], detail: str, content: cowbird.typedefs.JSON | None, content_type: str) Tuple[int, str, cowbird.typedefs.JSON][source]

Validates parameter types and formats required by valid_http() and raise_http().

Parameters:
  • http_class – any derived class from base HTTPException to verify

  • http_base – any derived sub-class(es) from base HTTPException as minimum requirement for http_class (ie: 2xx, 4xx, 5xx codes). Can be a single class of an iterable of possible requirements (any).

  • detail – additional message information (default: empty)

  • content – json formatted content to include

  • content_type – format in which to return the exception (one of cowbird.utils.SUPPORTED_ACCEPT_TYPES)

Raises:

HTTPInternalServerError – if any parameter is of invalid expected format

Returns http_code, detail, content:

parameters with corrected and validated format if applicable

cowbird.api.exception.format_content_json_str(http_code: int, detail: str, content: cowbird.typedefs.JSON, content_type: str) str[source]

Inserts the code, details, content and type within the body using json format. Includes also any other specified json formatted content in the body. Returns the whole json body as a single string for output.

Raises:

HTTPInternalServerError – if parsing of the json content failed

Returns:

formatted json content as string with added HTTP code and details

cowbird.api.exception.rewrite_content_type(content: str | cowbird.typedefs.JSON, content_type: str) Tuple[str, cowbird.typedefs.JSON | None][source]

Attempts to rewrite the type field inserted by various functions such as:

By applying the new value provided by content_type.

Returns:

Content with rewritten “type” (if possible) and converted to string directly insertable to a response body. Also provides the converted JSON body if applicable (original content was literal JSON or JSON-like string).

cowbird.api.exception.generate_response_http_format(http_class: Type[pyramid.httpexceptions.HTTPException], http_kwargs: cowbird.typedefs.ParamsType | None, content: cowbird.typedefs.JSON, content_type: str | None = CONTENT_TYPE_PLAIN, metadata: cowbird.typedefs.JSON | None = None) pyramid.httpexceptions.HTTPException[source]

Formats the HTTP response content according to desired content_type using provided HTTP code and content.

Parameters:
  • http_classHTTPException derived class to use for output (code, generic title/explanation, etc.)

  • http_kwargs – additional keyword arguments to pass to http_class when called

  • content – formatted JSON content or literal string content providing additional details for the response

  • content_type – one of cowbird.utils.SUPPORTED_ACCEPT_TYPES (default: cowbird.utils.CONTENT_TYPE_PLAIN)

  • metadata – request metadata to add to the response body. (see: cowbird.api.requests.get_request_info())

Returns:

http_class instance with requested information and content type if creation succeeds

Raises:

HTTPInternalServerError instance details about requested information and content type if creation fails