magpie.utils

Module Contents

Classes

ExtendedEnum

Utility enum.Enum methods.

SingletonMeta

A metaclass that creates a Singleton base class when called.

Functions

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

set_logger_config(logger: logging.Logger, force_stdout: bool = False, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None) → logging.Logger

Applies the provided logging configuration settings to the logger.

print_log(msg: magpie.typedefs.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

raise_log(msg: magpie.typedefs.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.

bool2str(value: Any) → magpie.typedefs.Str

Converts value to explicit "true" or "false" str with permissive variants comparison

islambda(func: Any) → bool

Evaluate if argument is a callable lambda expression.

isclass(obj: Any) → bool

Evaluate an object for class type (ie: class definition, not an instance nor any other type).

ismethod(obj: Any) → bool

Evaluate an object for method type (ie: class method reference.

make_dirs(path)

get_settings_from_config_ini(config_ini_path, ini_main_section_name='app:magpie_app')

get_json(response)

Retrieves the ‘JSON’ body of a response using the property/callable according to the response’s implementation.

get_header(header_name: magpie.typedefs.Str, header_container: magpie.typedefs.AnyHeadersType, default: Optional[magpie.typedefs.Str] = None, split: Optional[Union[magpie.typedefs.Str, List[magpie.typedefs.Str]]] = None) → Optional[magpie.typedefs.Str]

Retrieves header_name by fuzzy match (independently of upper/lower-case and underscore/dash) from various

convert_response(response: magpie.typedefs.AnyResponseType) → pyramid.response.Response

Converts a requests.Response object to an equivalent pyramid.response.Response object.

get_authenticate_headers(request: pyramid.request.Request, error_type: magpie.typedefs.Str = 'invalid_token') → Optional[magpie.typedefs.HeadersType]

Obtains all required headers by 401 responses based on executed request.

get_admin_cookies(container: magpie.typedefs.AnySettingsContainer, verify: bool = True, raise_message: Optional[magpie.typedefs.Str] = None) → magpie.typedefs.CookiesType

get_settings(container: Optional[magpie.typedefs.AnySettingsContainer], app: bool = False) → magpie.typedefs.SettingsType

Retrieve application settings from a supported container.

patch_magpie_url(container: magpie.typedefs.AnySettingsContainer) → magpie.typedefs.SettingsType

Updates potentially missing configuration settings for normal application execution.

get_magpie_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None) → magpie.typedefs.Str

Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings.

get_phoenix_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None) → magpie.typedefs.Str

Obtains the configured Phoenix URL entrypoint based on the various combinations of supported configuration settings.

get_twitcher_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None, hostname: Optional[magpie.typedefs.Str] = None) → magpie.typedefs.Str

Obtains the configured Twitcher URL entrypoint based on various combinations of supported configuration settings.

get_twitcher_protected_service_url(magpie_service_name, container=None, hostname=None)

Obtains the protected service URL behind Twitcher Proxy based on combination of supported configuration settings.

is_magpie_ui_path(request: pyramid.request.Request) → bool

Determines if the request path corresponds to any Magpie UI location.

fully_qualified_name(obj: Union[Any, Type[Any]]) → str

Obtains the '<module>.<name>' full path definition of the object to allow finding and importing it.

log_request_format(request: pyramid.request.Request) → magpie.typedefs.Str

log_request(event: pyramid.events.NewRequest) → None

Subscriber event that logs basic details about the incoming requests.

log_exception_tween(handler, registry)

Tween factory that logs any exception before re-raising it.

is_json_body(body: Any) → bool

Attributes

CONTENT_TYPE_ANY

CONTENT_TYPE_JSON

CONTENT_TYPE_FORM

CONTENT_TYPE_HTML

CONTENT_TYPE_PLAIN

CONTENT_TYPE_APP_XML

CONTENT_TYPE_TXT_XML

FORMAT_TYPE_MAPPING

SUPPORTED_ACCEPT_TYPES

SUPPORTED_FORMAT_TYPES

KNOWN_CONTENT_TYPES

LOGGER

magpie.utils.CONTENT_TYPE_ANY = */*[source]
magpie.utils.CONTENT_TYPE_JSON = application/json[source]
magpie.utils.CONTENT_TYPE_FORM = application/x-www-form-urlencoded[source]
magpie.utils.CONTENT_TYPE_HTML = text/html[source]
magpie.utils.CONTENT_TYPE_PLAIN = text/plain[source]
magpie.utils.CONTENT_TYPE_APP_XML = application/xml[source]
magpie.utils.CONTENT_TYPE_TXT_XML = text/xml[source]
magpie.utils.FORMAT_TYPE_MAPPING[source]
magpie.utils.SUPPORTED_ACCEPT_TYPES[source]
magpie.utils.SUPPORTED_FORMAT_TYPES[source]
magpie.utils.KNOWN_CONTENT_TYPES[source]
magpie.utils.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[source]

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

magpie.utils.LOGGER[source]
magpie.utils.set_logger_config(logger: logging.Logger, force_stdout: bool = False, message_format: Optional[magpie.typedefs.Str] = None, datetime_format: Optional[magpie.typedefs.Str] = None)logging.Logger[source]

Applies the provided logging configuration settings to the logger.

magpie.utils.print_log(msg: magpie.typedefs.Str, logger: Optional[logging.Logger] = None, level: int = logging.INFO, **kwargs: Any)None[source]

Logs the requested message to the logger and optionally enforce printing to the console according to configuration value defined by MAGPIE_LOG_PRINT.

magpie.utils.raise_log(msg: magpie.typedefs.Str, exception: Type[Exception] = Exception, logger: Optional[logging.Logger] = None, level: int = logging.ERROR)NoReturn[source]

Logs the provided message to the logger and raises the corresponding exception afterwards.

Raises

exception – whichever exception provided is raised systematically after logging.

magpie.utils.bool2str(value: Any)magpie.typedefs.Str[source]

Converts value to explicit "true" or "false" str with permissive variants comparison that can represent common falsy or truthy values.

magpie.utils.islambda(func: Any)bool[source]

Evaluate if argument is a callable lambda expression.

magpie.utils.isclass(obj: Any)bool[source]

Evaluate an object for class type (ie: class definition, not an instance nor any other type).

magpie.utils.ismethod(obj: Any)bool[source]

Evaluate an object for method type (ie: class method reference.

magpie.utils.make_dirs(path)[source]
magpie.utils.get_settings_from_config_ini(config_ini_path, ini_main_section_name='app:magpie_app')[source]
magpie.utils.get_json(response)[source]

Retrieves the ‘JSON’ body of a response using the property/callable according to the response’s implementation.

magpie.utils.get_header(header_name: magpie.typedefs.Str, header_container: magpie.typedefs.AnyHeadersType, default: Optional[magpie.typedefs.Str] = None, split: Optional[Union[magpie.typedefs.Str, List[magpie.typedefs.Str]]] = None)Optional[magpie.typedefs.Str][source]

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=';').

Parameters
  • header_name – header to find.

  • header_container – where to look for header_name.

  • default – value to returned if header_container is invalid or header_name could not be found.

  • split – character(s) to use to split the found header_name.

magpie.utils.convert_response(response: magpie.typedefs.AnyResponseType)pyramid.response.Response[source]

Converts a requests.Response object to an equivalent pyramid.response.Response object.

Content of the response is expected to be JSON.

Parameters

response – response to be converted

Returns

converted response

magpie.utils.get_authenticate_headers(request: pyramid.request.Request, error_type: magpie.typedefs.Str = 'invalid_token')Optional[magpie.typedefs.HeadersType][source]

Obtains all required headers by 401 responses based on executed request.

Parameters
  • request – request that was sent to attempt authentication or access which must respond with Unauthorized.

  • error_type – Additional detail of the cause of error. Must be one of (invalid_request, invalid_token, insufficient_scope).

magpie.utils.get_admin_cookies(container: magpie.typedefs.AnySettingsContainer, verify: bool = True, raise_message: Optional[magpie.typedefs.Str] = None)magpie.typedefs.CookiesType[source]
magpie.utils.get_settings(container: Optional[magpie.typedefs.AnySettingsContainer], app: bool = False)magpie.typedefs.SettingsType[source]

Retrieve application settings from a supported container.

Parameters
  • container – supported container with an handle to application settings.

  • app – allow retrieving from current thread registry if no container was defined.

Returns

found application settings dictionary.

Raises

TypeError – when no application settings could be found or unsupported container.

magpie.utils.patch_magpie_url(container: magpie.typedefs.AnySettingsContainer)magpie.typedefs.SettingsType[source]

Updates potentially missing configuration settings for normal application execution.

magpie.utils.get_magpie_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None)magpie.typedefs.Str[source]

Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings.

See also

Documentation section Application Settings for available setting combinations.

Parameters

container – container that provides access to application settings.

Returns

resolved Magpie URL

magpie.utils.get_phoenix_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None)magpie.typedefs.Str[source]

Obtains the configured Phoenix URL entrypoint based on the various combinations of supported configuration settings.

See also

Documentation section Phoenix Settings for available setting combinations.

Parameters

container – container that provides access to application settings.

Returns

resolved Phoenix URL

magpie.utils.get_twitcher_url(container: Optional[magpie.typedefs.AnySettingsContainer] = None, hostname: Optional[magpie.typedefs.Str] = None)magpie.typedefs.Str[source]

Obtains the configured Twitcher URL entrypoint based on various combinations of supported configuration settings.

See also

Documentation section Twitcher Settings for available setting combinations.

Parameters
  • container – container that provides access to application settings.

  • hostname – override literal hostname to generate the URL instead of resolving using settings.

Returns

resolved Twitcher URL

magpie.utils.get_twitcher_protected_service_url(magpie_service_name, container=None, hostname=None)[source]

Obtains the protected service URL behind Twitcher Proxy based on combination of supported configuration settings.

See also

Documentation section Twitcher Settings for available setting combinations.

Parameters
  • magpie_service_name – name of the service to employ in order to form the URL path behind the proxy.

  • container – container that provides access to application settings.

  • hostname – override literal hostname to generate the URL instead of resolving using settings.

Returns

resolved Twitcher Proxy protected service URL

magpie.utils.is_magpie_ui_path(request: pyramid.request.Request)bool[source]

Determines if the request path corresponds to any Magpie UI location.

magpie.utils.fully_qualified_name(obj: Union[Any, Type[Any]])str[source]

Obtains the '<module>.<name>' full path definition of the object to allow finding and importing it.

magpie.utils.log_request_format(request: pyramid.request.Request)magpie.typedefs.Str[source]
magpie.utils.log_request(event: pyramid.events.NewRequest)None[source]

Subscriber event that logs basic details about the incoming requests.

magpie.utils.log_exception_tween(handler, registry)[source]

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.

magpie.utils.is_json_body(body: Any)bool[source]
class magpie.utils.ExtendedEnum[source]

Bases: enum.Enum

Utility enum.Enum methods.

Create an extended enum with these utilities as follows:

class CustomEnum(ExtendedEnum):
    ItemA = "A"
    ItemB = "B"
classmethod names(cls)List[magpie.typedefs.Str][source]

Returns the member names assigned to corresponding enum elements.

classmethod values(cls)List[magpie.typedefs.AnyKey][source]

Returns the literal values assigned to corresponding enum elements.

classmethod get(cls: magpie.typedefs.AnyKey, key_or_value: Optional[Any], default=None)Optional[_TC][source]

Finds an enum entry by defined name or its value.

Returns the entry directly if it is already a valid enum.

class magpie.utils.SingletonMeta[source]

Bases: type

A metaclass that creates a Singleton base class when called.

Create a class such that:

@six.add_metaclass(SingletonMeta)
class A(object):
    pass

@six.add_metaclass(SingletonMeta)
class B(object):
    pass

a1 = A()
a2 = A()
b1 = B()
b2 = B()
a1 is a2    # True
b1 is b2    # True
a1 is b1    # False
_instances[source]
__call__(cls, *args, **kwargs)[source]

Call self as a function.