magpie.api.exception ==================== .. py:module:: magpie.api.exception Attributes ---------- .. autoapisummary:: magpie.api.exception.CONTENT_TYPE_ANY magpie.api.exception.CONTENT_TYPE_APP_XML magpie.api.exception.CONTENT_TYPE_HTML magpie.api.exception.CONTENT_TYPE_JSON magpie.api.exception.CONTENT_TYPE_PLAIN magpie.api.exception.CONTENT_TYPE_TXT_XML magpie.api.exception.SUPPORTED_ACCEPT_TYPES magpie.api.exception.LOGGER magpie.api.exception.RAISE_RECURSIVE_SAFEGUARD_MAX magpie.api.exception.RAISE_RECURSIVE_SAFEGUARD_COUNT magpie.api.exception.PARAM_REGEX magpie.api.exception.SCOPE_REGEX magpie.api.exception.EMAIL_REGEX magpie.api.exception.UUID_REGEX magpie.api.exception.URL_REGEX magpie.api.exception.INDEX_REGEX magpie.api.exception.Pattern Functions --------- .. autoapisummary:: magpie.api.exception.get_header magpie.api.exception.get_logger magpie.api.exception.isclass magpie.api.exception.islambda magpie.api.exception.verify_param magpie.api.exception.apply_param_content magpie.api.exception.evaluate_call magpie.api.exception.valid_http magpie.api.exception.raise_http magpie.api.exception.validate_params magpie.api.exception.format_content_json_str magpie.api.exception.rewrite_content_type magpie.api.exception.generate_response_http_format Module Contents --------------- .. py:data:: CONTENT_TYPE_ANY :value: '*/*' .. py:data:: CONTENT_TYPE_APP_XML :value: 'application/xml' .. py:data:: CONTENT_TYPE_HTML :value: 'text/html' .. py:data:: CONTENT_TYPE_JSON :value: 'application/json' .. py:data:: CONTENT_TYPE_PLAIN :value: 'text/plain' .. py:data:: CONTENT_TYPE_TXT_XML :value: 'text/xml' .. py:data:: SUPPORTED_ACCEPT_TYPES .. py:function:: get_header(header_name: magpie.typedefs.Str, header_container: magpie.typedefs.AnyHeadersType, default: (Optional[magpie.typedefs.Str], Optional[Union[magpie.typedefs.Str, List[magpie.typedefs.Str]]], bool) = None, split: Optional[Union[magpie.typedefs.Str, List[magpie.typedefs.Str]]] = None, multi: bool = False, pop: bool = False) -> Optional[Union[magpie.typedefs.Str, List[magpie.typedefs.Str]]] Retrieves ``header_name`` by fuzzy match (independently of upper/lower-case and underscore/dash) from various framework implementations of ``Headers``. If ``split`` is specified, the matched ``header_name`` is first split with it and the first item is returned. This allows to parse complex headers (e.g.: ``text/plain; charset=UTF-8`` to ``text/plain`` with ``split=';'``). :param header_name: Header to find. :param header_container: Where to look for `header_name`. :param default: Value to returned if `header_container` is invalid or `header_name` could not be found. :param split: Character(s) to use to split the *found* `header_name`. :param multi: Return extracted header as array of multiple values or return a single value on fist match. :param pop: Remove the header from the container if found. :returns: Found header value(s) if applicable. .. py:function:: get_logger(name: magpie.typedefs.Str, level: Optional[int] = None, force_stdout: bool = None, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None) -> logging.Logger Immediately sets the logger level to avoid duplicate log outputs from the `root logger` and `this logger` when `level` is ``logging.NOTSET``. .. py:function:: isclass(obj: Any) -> bool Evaluate an object for :class:`class` type (ie: class definition, not an instance nor any other type). .. py:function:: islambda(func: Any) -> bool Evaluate if argument is a callable :class:`lambda` expression. .. py:data:: LOGGER .. py:data:: RAISE_RECURSIVE_SAFEGUARD_MAX :value: 5 .. py:data:: RAISE_RECURSIVE_SAFEGUARD_COUNT :value: 0 .. py:data:: PARAM_REGEX .. py:data:: SCOPE_REGEX .. py:data:: EMAIL_REGEX .. py:data:: UUID_REGEX .. py:data:: URL_REGEX .. py:data:: INDEX_REGEX .. py:data:: Pattern .. py:function:: verify_param(param: Any, param_compare: Optional[Union[Any, List[Any]]] = None, param_name: Optional[magpie.typedefs.Str] = None, param_content: Optional[magpie.typedefs.JSON] = None, with_param: bool = True, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPBadRequest, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, msg_on_fail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None, 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 Evaluate various parameter combinations given the requested verification flags. Given a failing verification, directly raises the specified :paramref:`http_error`. Invalid usage exceptions generated by this verification process are treated as :class:`HTTPInternalServerError`. Exceptions are generated using the standard output method. :param param: parameter value to evaluate :param param_compare: Other value(s) to test :paramref:`param` against. Can be an iterable (single value resolved as iterable unless ``None``). To test for ``None`` type, use :paramref:`is_none`/:paramref:`not_none` flags instead. :param param_name: name of the tested parameter returned in response if specified for debugging purposes :param param_content: Additional JSON content to apply to generated error content on raise when :paramref:`with_param` is ``True``. Must be JSON serializable. Provided content can override generated error parameter if matching fields. :param with_param: On raise, adds values of :paramref:`param`, :paramref:`param_name` and :paramref:`param_compare`, as well as additional failing conditions metadata to the JSON response body for each of the corresponding value. :param http_error: derived exception to raise on test failure (default: :class:`HTTPBadRequest`) :param http_kwargs: additional keyword arguments to pass to :paramref:`http_error` called in case of HTTP exception :param msg_on_fail: message details to return in HTTP exception if flag condition failed :param content: json formatted additional content to provide in case of exception :param content_type: format in which to return the exception (one of :py:data:`magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :param not_none: test that :paramref:`param` is not ``None`` type :param not_empty: test that :paramref:`param` is not an empty iterable (string, list, set, etc.) :param not_in: test that :paramref:`param` does not exist in :paramref:`param_compare` values :param not_equal: test that :paramref:`param` is not equal to :paramref:`param_compare` value :param is_true: test that :paramref:`param` is ``True`` :param is_false: test that :paramref:`param` is ``False`` :param is_none: test that :paramref:`param` is ``None`` type :param is_empty: test `param` for an empty iterable (string, list, set, etc.) :param is_in: test that :paramref:`param` exists in :paramref:`param_compare` values :param is_equal: test that :paramref:`param` equals :paramref:`param_compare` value :param is_type: test that :paramref:`param` is of same type as specified by :paramref:`param_compare` type :param matches: test that :paramref:`param` matches the regex specified by :paramref:`param_compare` value :raises HTTPError: if tests fail, specified exception is raised (default: :class:`HTTPBadRequest`) :raises HTTPInternalServerError: for evaluation error :return: nothing if all tests passed .. py:function:: apply_param_content(content: magpie.typedefs.JSON, param: Any, param_compare: Any, param_name: magpie.typedefs.Str, with_param: bool, param_content: Optional[magpie.typedefs.JSON], needs_compare: bool, needs_iterable: bool, is_type: bool, fail_conditions: magpie.typedefs.JSON) -> magpie.typedefs.JSON Formats and applies the failing parameter conditions and results to returned JSON content according to flags. .. seealso:: :func:`verify_param` .. py:function:: evaluate_call(call: Callable[[], Any], fallback: Optional[Callable[[], None]] = None, http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, msg_on_fail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None) -> Any Evaluates the specified :paramref:`call` with a wrapped HTTP exception handling. On failure, tries to call. :paramref:`fallback` if specified, and finally raises the specified :paramref:`http_error`. Any potential error generated by :paramref:`fallback` or :paramref:`http_error` themselves are treated as :class:`HTTPInternalServerError`. Exceptions are generated using the standard output method formatted based on specified :paramref:`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) :param call: function to call, *MUST* be specified as `lambda: ` :param fallback: function to call (if any) when `call` failed, *MUST* be `lambda: ` :param http_error: alternative exception to raise on `call` failure :param http_kwargs: additional keyword arguments to pass to `http_error` if called in case of HTTP exception :param msg_on_fail: message details to return in HTTP exception if `call` failed :param content: json formatted additional content to provide in case of exception :param content_type: format in which to return the exception (one of `magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :raises http_error: on `call` failure :raises `HTTPInternalServerError`: on `fallback` failure :return: whichever return value `call` might have if no exception occurred .. py:function:: valid_http(http_success: Union[Type[pyramid.httpexceptions.HTTPSuccessful], Type[pyramid.httpexceptions.HTTPRedirection]] = HTTPOk, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: Optional[magpie.typedefs.Str] = '', content: Optional[magpie.typedefs.JSON] = None, content_type: Optional[magpie.typedefs.Str] = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None) -> Union[pyramid.httpexceptions.HTTPSuccessful, pyramid.httpexceptions.HTTPRedirection] Returns successful HTTP with standardized information formatted with content type. (see :func:`raise_http` for HTTP error calls) :param http_success: any derived class from *valid* HTTP codes (<400) (default: `HTTPOk`) :param http_kwargs: additional keyword arguments to pass to `http_success` when called :param detail: additional message information (default: empty) :param content: json formatted content to include :param content_type: format in which to return the exception (one of `magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :returns: formatted successful response with additional details and HTTP code .. py:function:: raise_http(http_error: Type[pyramid.httpexceptions.HTTPError] = HTTPInternalServerError, http_kwargs: Optional[magpie.typedefs.ParamsType] = None, detail: magpie.typedefs.Str = '', content: Optional[magpie.typedefs.JSON] = None, content_type: magpie.typedefs.Str = CONTENT_TYPE_JSON, metadata: Optional[magpie.typedefs.JSON] = None, nothrow: bool = False) -> NoReturn 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). .. seealso:: :func:`valid_http` for HTTP successful calls :param http_error: any derived class from base `HTTPError` (default: `HTTPInternalServerError`) :param http_kwargs: additional keyword arguments to pass to `http_error` if called in case of HTTP exception :param detail: additional message information (default: empty) :param content: JSON formatted content to include :param content_type: format in which to return the exception (one of `magpie.common.SUPPORTED_ACCEPT_TYPES`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :param 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` .. py:function:: validate_params(http_class: Type[pyramid.httpexceptions.HTTPException], http_base: Union[Type[pyramid.httpexceptions.HTTPException], Iterable[Type[pyramid.httpexceptions.HTTPException]]], detail: magpie.typedefs.Str, content: Optional[magpie.typedefs.JSON], content_type: magpie.typedefs.Str) -> Tuple[int, magpie.typedefs.Str, magpie.typedefs.JSON] Validates parameter types and formats required by :func:`valid_http` and :func:`raise_http`. :param http_class: any derived class from base `HTTPException` to verify :param 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). :param detail: additional message information (default: empty) :param content: json formatted content to include :param content_type: format in which to return the exception (one of `magpie.common.SUPPORTED_ACCEPT_TYPES`) :raise `HTTPInternalServerError`: if any parameter is of invalid expected format :returns http_code, detail, content: parameters with corrected and validated format if applicable .. py:function:: format_content_json_str(http_code: int, detail: magpie.typedefs.Str, content: magpie.typedefs.JSON, content_type: magpie.typedefs.Str) -> magpie.typedefs.Str 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. :raise `HTTPInternalServerError`: if parsing of the json content failed. :returns: formatted JSON content as string with added HTTP code and details. .. py:function:: rewrite_content_type(content: Union[magpie.typedefs.Str, magpie.typedefs.JSON], content_type: magpie.typedefs.Str) -> Tuple[magpie.typedefs.Str, Optional[magpie.typedefs.JSON]] Attempts to rewrite the ``type`` field inserted by various functions such as: - :func:`format_content_json_str` - :func:`raise_http` - :func:`valid_http` By applying the new value provided by :paramref:`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). .. py:function:: generate_response_http_format(http_class: Type[pyramid.httpexceptions.HTTPException], http_kwargs: Optional[magpie.typedefs.ParamsType], content: magpie.typedefs.JSON, content_type: Optional[magpie.typedefs.Str] = CONTENT_TYPE_PLAIN, metadata: Optional[magpie.typedefs.JSON] = None) -> pyramid.httpexceptions.HTTPException Formats the HTTP response content according to desired ``content_type`` using provided HTTP code and content. :param http_class: `HTTPException` derived class to use for output (code, generic title/explanation, etc.) :param http_kwargs: additional keyword arguments to pass to `http_class` when called :param content: formatted JSON content or literal string content providing additional details for the response :param content_type: one of `magpie.common.SUPPORTED_ACCEPT_TYPES` (default: `magpie.common.CONTENT_TYPE_PLAIN`) :param metadata: request metadata to add to the response body. (see: :func:`magpie.api.requests.get_request_info`) :return: `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