cowbird.utils ============= .. py:module:: cowbird.utils Attributes ---------- .. autoapisummary:: cowbird.utils.CONTENT_TYPE_ANY cowbird.utils.CONTENT_TYPE_JSON cowbird.utils.CONTENT_TYPE_FORM cowbird.utils.CONTENT_TYPE_HTML cowbird.utils.CONTENT_TYPE_PLAIN cowbird.utils.CONTENT_TYPE_APP_XML cowbird.utils.CONTENT_TYPE_TXT_XML cowbird.utils.FORMAT_TYPE_MAPPING cowbird.utils.SUPPORTED_ACCEPT_TYPES cowbird.utils.SUPPORTED_FORMAT_TYPES cowbird.utils.KNOWN_CONTENT_TYPES cowbird.utils.CLI_MODE_CFG cowbird.utils.USE_TEST_CELERY_APP_CFG cowbird.utils.EnumClassType cowbird.utils.LOGGER cowbird.utils.SingletonMetaType cowbird.utils.null Classes ------- .. autoapisummary:: cowbird.utils.ExtendedEnum cowbird.utils.SingletonMeta cowbird.utils.NullType Functions --------- .. autoapisummary:: cowbird.utils.get_logger cowbird.utils.set_logger_config cowbird.utils.print_log cowbird.utils.raise_log cowbird.utils.bool2str cowbird.utils.bytes2str cowbird.utils.islambda cowbird.utils.configure_celery cowbird.utils.get_app_config cowbird.utils.get_settings_from_config_ini cowbird.utils.get_registry cowbird.utils.get_json cowbird.utils.get_header cowbird.utils.convert_response cowbird.utils.get_settings cowbird.utils.fully_qualified_name cowbird.utils.log_request_format cowbird.utils.log_request cowbird.utils.log_exception_tween cowbird.utils.is_json_body cowbird.utils.is_null cowbird.utils.get_config_path cowbird.utils.get_ssl_verify cowbird.utils.get_timeout cowbird.utils.apply_new_path_permissions cowbird.utils.update_filesystem_permissions cowbird.utils.apply_default_path_ownership Module Contents --------------- .. py:data:: CONTENT_TYPE_ANY :value: '*/*' .. py:data:: CONTENT_TYPE_JSON :value: 'application/json' .. py:data:: CONTENT_TYPE_FORM :value: 'application/x-www-form-urlencoded' .. py:data:: CONTENT_TYPE_HTML :value: 'text/html' .. py:data:: CONTENT_TYPE_PLAIN :value: 'text/plain' .. py:data:: CONTENT_TYPE_APP_XML :value: 'application/xml' .. py:data:: CONTENT_TYPE_TXT_XML :value: 'text/xml' .. py:data:: FORMAT_TYPE_MAPPING .. py:data:: SUPPORTED_ACCEPT_TYPES .. py:data:: SUPPORTED_FORMAT_TYPES .. py:data:: KNOWN_CONTENT_TYPES :value: ['application/json', 'text/html', 'text/plain', 'application/xml', 'text/xml',... .. py:data:: CLI_MODE_CFG :value: 'cli_mode' .. py:data:: USE_TEST_CELERY_APP_CFG :value: 'use_test_celery_app' .. py:data:: EnumClassType .. py:function:: get_logger(name: str, level: Optional[int] = None, force_stdout: bool = None, message_format: Optional[str] = None, datetime_format: Optional[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:data:: LOGGER .. py:function:: set_logger_config(logger: logging.Logger, force_stdout: bool = False, message_format: Optional[str] = None, datetime_format: Optional[str] = None) -> logging.Logger Applies the provided logging configuration settings to the logger. .. py:function:: print_log(msg: str, logger: Optional[logging.Logger] = None, level: int = logging.INFO, **kwargs: Any) -> None Logs the requested message to the logger and optionally enforce printing to the console according to configuration value defined by ``COWBIRD_LOG_PRINT``. .. py:function:: raise_log(msg: str, exception: Type[Exception] = Exception, logger: Optional[logging.Logger] = None, level: int = logging.ERROR) -> NoReturn Logs the provided message to the logger and raises the corresponding exception afterwards. :raises exception: whichever exception provided is raised systematically after logging. .. py:function:: bool2str(value: Any) -> str Converts :paramref:`value` to explicit ``"true"`` or ``"false"`` :class:`str` with permissive variants comparison that can represent common falsy or truthy values. .. py:function:: bytes2str(string: Union[str, bytes]) -> str Ensures a string is represented in UTF-8. .. py:function:: islambda(func: Any) -> bool Evaluate if argument is a callable :class:`lambda` expression. .. py:function:: configure_celery(config: pyramid.config.Configurator, config_ini: str) -> None .. py:function:: get_app_config(container: cowbird.typedefs.AnySettingsContainer) -> pyramid.config.Configurator Generates application configuration with all required utilities and settings configured. .. py:function:: get_settings_from_config_ini(config_ini_path: str, section: Optional[str] = None) -> cowbird.typedefs.SettingsType Loads configuration INI settings with additional handling. .. py:function:: get_registry(container: cowbird.typedefs.AnyRegistryContainer, nothrow: bool = False) -> Optional[pyramid.registry.Registry] Retrieves the application ``registry`` from various containers referencing to it. .. py:function:: get_json(response: cowbird.typedefs.AnyResponseType) -> cowbird.typedefs.JSON Retrieves the 'JSON' body of a response using the property/callable according to the response's implementation. .. py:function:: get_header(header_name: str, header_container: cowbird.typedefs.AnyHeadersType, default: Optional[str] = None, split: Optional[Union[str, List[str]]] = None) -> Optional[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`. .. py:function:: convert_response(response: cowbird.typedefs.AnyResponseType) -> pyramid.response.Response Converts a :class:`requests.Response` object to an equivalent :class:`pyramid.response.Response` object. Content of the :paramref:`response` is expected to be JSON. :param response: response to be converted :returns: converted response .. py:function:: get_settings(container: Optional[cowbird.typedefs.AnySettingsContainer], app: bool = False) -> cowbird.typedefs.SettingsType Retrieve application settings from a supported container. :param container: supported container with a handle to application settings. :param app: allow retrieving from current thread registry if no container was defined. :returns: found application settings dictionary. :raise TypeError: when no application settings could be found or unsupported container. .. py:function:: fully_qualified_name(obj: Union[Any, Type[Any]]) -> str Obtains the ``'.'`` full path definition of the object to allow finding and importing it. .. py:function:: log_request_format(request: pyramid.request.Request) -> str .. py:function:: log_request(event: pyramid.events.NewRequest) -> None Subscriber event that logs basic details about the incoming requests. .. py:function:: log_exception_tween(handler: Callable[[pyramid.request.Request], cowbird.typedefs.AnyResponseType], registry: pyramid.registry.Registry) -> Callable[[pyramid.request.Request], cowbird.typedefs.AnyResponseType] Tween factory that logs any exception before re-raising it. Application errors are marked as ``ERROR`` while non-critical HTTP errors are marked as ``WARNING``. .. py:function:: is_json_body(body: Any) -> bool .. py:class:: ExtendedEnum Bases: :py:obj:`enum.Enum` Utility :class:`enum.Enum` methods. Create an extended enum with these utilities as follows:: class CustomEnum(ExtendedEnum): ItemA = "A" ItemB = "B" .. py:method:: names() -> List[str] :classmethod: Returns the member names assigned to corresponding enum elements. .. py:method:: values() -> List[cowbird.typedefs.AnyKey] :classmethod: Returns the literal values assigned to corresponding enum elements. .. py:method:: get(key_or_value: Union[cowbird.typedefs.AnyKey, EnumClassType], default: Optional[Any] = None) -> Optional[EnumClassType] :classmethod: Finds an enum entry by defined name or its value. Returns the entry directly if it is already a valid enum. .. py:data:: SingletonMetaType :type: typing_extensions.TypeAlias :value: 'SingletonMeta' .. py:class:: SingletonMeta Bases: :py:obj:`type` A metaclass that creates a Singleton base class when called. Create a class such that. .. code-block:: python class A(object, metaclass=SingletonMeta): pass class B(object, metaclass=SingletonMeta): pass a1 = A() a2 = A() b1 = B() b2 = B() a1 is a2 # True b1 is b2 # True a1 is b1 # False .. py:attribute:: _instances :type: Dict[SingletonMetaType, SingletonMetaType] .. py:method:: __call__(*args: Any, **kwargs: Any) -> SingletonMetaType .. py:class:: NullType Bases: :py:obj:`object` Represents a null value to differentiate from None. .. py:method:: __repr__() -> str .. py:method:: __nonzero__() -> bool :staticmethod: .. py:attribute:: __bool__ .. py:attribute:: __len__ .. py:data:: null .. py:function:: is_null(item: Any) -> bool .. py:function:: get_config_path(container: Optional[cowbird.typedefs.AnySettingsContainer] = None) -> str .. py:function:: get_ssl_verify(container: Optional[cowbird.typedefs.AnySettingsContainer] = None) -> bool .. py:function:: get_timeout(container: Optional[cowbird.typedefs.AnySettingsContainer] = None) -> int .. py:function:: apply_new_path_permissions(path: str, is_readable: bool, is_writable: bool, is_executable: bool) -> None Applies new permissions to a path, if required. .. py:function:: update_filesystem_permissions(permission: int, is_readable: bool, is_writable: bool, is_executable: bool) -> int Applies/remove read, write and execute permissions (on ``others`` only) to the input file system permissions. Note that ``others`` permissions are used instead of the ``user``/``group`` permissions, to manage the user's data access. See :ref:`Components - Usage of 'others' permissions ` for more details on the usage of ``others`` permissions. .. py:function:: apply_default_path_ownership(path: str) -> None Applies default ownership to a path, if required.