magpie.ui.utils¶
Attributes¶
Classes¶
Supported statuses of user-group relationships. |
|
Base methods for Magpie UI pages. |
|
Regroups multiple administration-level operations to be dispatched to the API requests. |
Functions¶
|
Obtains additional exception content details about the |
|
Obtains additional content details about the |
|
|
|
Search in order for matched value of |
|
Masks away any credential matched against |
|
Retrieves |
|
Retrieves the 'JSON' body of a response using the property/callable according to the response's implementation. |
|
Immediately sets the logger level to avoid duplicate log outputs from the root logger and this logger when |
|
Obtains the configured Magpie URL entrypoint based on the various combinations of supported configuration settings. |
|
|
|
Use a pyramid sub-request to request Magpie API routes via the UI. This avoids max retries and closed connections |
|
Redirects the contents to be rendered by the UI 'error' page. |
|
Decorator that encapsulates the operation in a try/except block, and redirects the response to the UI error page |
Module Contents¶
- magpie.ui.utils.get_exception_info(response: pyramid.httpexceptions.HTTPException | pyramid.request.Request | pyramid.response.Response, content: magpie.typedefs.JSON | None = None, exception_details: bool = False) magpie.typedefs.JSON[source]¶
Obtains additional exception content details about the
responseaccording to available information.
- magpie.ui.utils.get_request_info(request: pyramid.request.Request | pyramid.httpexceptions.HTTPException, default_message: magpie.typedefs.Str | None = None, exception_details: bool = False) magpie.typedefs.JSON[source]¶
Obtains additional content details about the
requestaccording to available information.
- magpie.ui.utils.get_logged_user(request: pyramid.request.Request) magpie.models.User | None[source]¶
- magpie.ui.utils.get_constant(constant_name: magpie.typedefs.Str, settings_container: magpie.typedefs.AnySettingsContainer | None = None, settings_name: magpie.typedefs.Str | None = None, default_value: magpie.typedefs.SettingValue | None = None, raise_not_set: bool = True, raise_missing: bool = True, print_missing: bool = False, empty_missing: bool = False) magpie.typedefs.SettingValue[source]¶
- Search in order for matched value of
constant_name: search in
MAGPIE_CONSTANTSsearch in settings if specified
search alternative setting names (see below)
search in
magpie.constantsdefinitionssearch in environment variables
Parameter
constant_nameis expected to have the formatMAGPIE_[VARIABLE_NAME]although any value can be passed to retrieve generic settings from all above-mentioned search locations.If
settings_nameis provided as alternative name, it is used as is to search for results ifconstant_namewas not found. Otherwise,magpie.[variable_name]is used for additional search when the formatMAGPIE_[VARIABLE_NAME]was used forconstant_name(i.e.:MAGPIE_ADMIN_USERwill also search formagpie.admin_userand so on for corresponding constants).- Parameters:
constant_name – key to search for a value
settings_container – WSGI application settings container (if not provided, uses found one in current thread)
settings_name – alternative name for settings if specified
default_value – default value to be returned if not found anywhere, and exception raises are disabled.
raise_not_set – raise an exception if the found key is
None, search until last case if others areNoneraise_missing – raise exception if key is not found anywhere
print_missing – print message if key is not found anywhere, return
Noneempty_missing – consider an empty value for an existing key as if it was missing (i.e.: as if not set).
- Returns:
found value or default_value
- Raises:
ValueError – if resulting value is invalid based on options (by default raise missing/empty/
Nonevalue)LookupError – if no appropriate value could be found from all search locations (according to options)
- Search in order for matched value of
- class magpie.ui.utils.UserGroupStatus[source]¶
Bases:
magpie.utils.FlexibleNameEnumSupported statuses of user-group relationships.
- ALL = 'all'¶
- ACTIVE = 'active'¶
- PENDING = 'pending'¶
- magpie.ui.utils.mask_credentials(container: magpie.typedefs.JSON, redact: magpie.typedefs.Str = '[REDACTED]', flags: List[magpie.typedefs.Str] | None = None, parent: magpie.typedefs.Str | None = None) magpie.typedefs.JSON[source]¶
Masks away any credential matched against
flagsrecursively from JSONcontainer.Matched credential entries are replaced by
redact. List items are all replaced by the sameredactwhen theirparentfield name is matched.- Parameters:
container – JSON container to mask. If starting with a list on top-level, first level children will not be masked unless parent is provided.
redact – string by which to replace flagged fields.
flags – field names (partial matches) to flag for masking.
parent – reference to contained elements if in a listing format rather than mapping.
- Returns:
masked credentials JSON container.
- magpie.ui.utils.get_header(header_name: magpie.typedefs.Str, header_container: magpie.typedefs.AnyHeadersType, default: magpie.typedefs.Str | None, magpie.typedefs.Str | List[magpie.typedefs.Str] | None, bool = None, split: magpie.typedefs.Str | List[magpie.typedefs.Str] | None = None, multi: bool = False, pop: bool = False) magpie.typedefs.Str | List[magpie.typedefs.Str] | None[source]¶
Retrieves
header_nameby fuzzy match (independently of upper/lower-case and underscore/dash) from various framework implementations ofHeaders.If
splitis specified, the matchedheader_nameis first split with it and the first item is returned. This allows to parse complex headers (e.g.:text/plain; charset=UTF-8totext/plainwithsplit=';').- 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.
multi – Return extracted header as array of multiple values or return a single value on fist match.
pop – Remove the header from the container if found.
- Returns:
Found header value(s) if applicable.
- magpie.ui.utils.get_json(request_or_response: magpie.typedefs.AnyRequestType | magpie.typedefs.AnyResponseType) magpie.typedefs.JSON[source]¶
Retrieves the ‘JSON’ body of a response using the property/callable according to the response’s implementation.
- magpie.ui.utils.get_logger(name: magpie.typedefs.Str, level: int | None = None, force_stdout: bool = None, message_format: magpie.typedefs.Str | None = None, datetime_format: magpie.typedefs.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.
- magpie.ui.utils.get_magpie_url(container: magpie.typedefs.AnySettingsContainer | None = 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.ui.utils.check_response(response: magpie.typedefs.AnyResponseType) magpie.typedefs.AnyResponseType[source]¶
- Returns:
response if the HTTP status code is successful.
- Raises:
HTTPError – (of appropriate type) if the response corresponds to an HTTP error code
- magpie.ui.utils.request_api(request: pyramid.request.Request, path: magpie.typedefs.Str, method: magpie.typedefs.Str = 'GET', data: magpie.typedefs.JSON | magpie.typedefs.Str | None = None, headers: magpie.typedefs.HeadersType | None = None, cookies: magpie.typedefs.CookiesType | None = None) magpie.typedefs.AnyResponseType[source]¶
Use a pyramid sub-request to request Magpie API routes via the UI. This avoids max retries and closed connections when using 1 worker (eg: during tests).
Some information is retrieved from
requestto pass down to the sub-request (eg: cookies). If they are passed as argument, corresponding values will override the ones found inrequest.All sub-requests to the API are assumed to be
magpie.common.CONTENT_TYPE_JSONunless explicitly overridden withheaders. Headers are also looked for additionalSet-Cookieheader in case they need to be passed down tocookies.- Parameters:
request – incoming Magpie UI request that requires sub-request to Magpie API, to retrieve required details.
path – local Magpie API path (relative to root without URL).
method – HTTP method to send the API sub-request.
data – JSON dictionary or literal string content of the request body.
headers – override headers to employ for the API sub-request. Defaults to JSON Accept & Content-Type headers.
cookies – Override cookies to employ for the API sub-request. Defaults to current logged user. For empty cookies (no user), explicitly provide an empty dictionary.
- magpie.ui.utils.redirect_error(request: pyramid.request.Request, code: int = None, content: magpie.typedefs.JSON | None = None) magpie.typedefs.AnyResponseType[source]¶
Redirects the contents to be rendered by the UI ‘error’ page.
- Parameters:
request – incoming request that resulted into some kind of error.
code – explicit HTTP status code for the error response, extracted from contents if otherwise available.
content – any body content provided as error response from the API.
- magpie.ui.utils.handle_errors(func: Callable) Callable[source]¶
Decorator that encapsulates the operation in a try/except block, and redirects the response to the UI error page with API error contents.
In worst case scenario where the operation cannot figure out what to do with the exception response, raise the most basic
HTTPInternalServerErrorthat can be formulated from available details.See also
- class magpie.ui.utils.BaseViews(request)[source]¶
Bases:
objectBase methods for Magpie UI pages.
- MAGPIE_FIXED_USERS_REFS = [][source]¶
Special User that cannot have any relationship edited.
This includes both Group memberships and Permission references.
- MAGPIE_USER_PWD_LOCKED = [][source]¶
Special User that could self-edit themselves, but is disabled since conflicting with other policies.
- MAGPIE_USER_PWD_DISABLED = [][source]¶
Special User where password cannot be edited (managed by Magpie configuration settings).
- MAGPIE_ANONYMOUS_GROUP = None[source]¶
Reference to
magpie.constants.MAGPIE_ANONYMOUS_GROUPfor convenience in UI pages.
- add_template_data(data: Dict[magpie.typedefs.Str, Any] | None = None) Dict[magpie.typedefs.Str, Any][source]¶
Adds required template data for the ‘heading’ mako template applied to every UI page.
- render(template: magpie.typedefs.Str, data: Dict[magpie.typedefs.Str, Any] | None = None) pyramid.response.Response[source]¶
Render the response with an explicit Mako template reference.
Views that are decorated by
pyramid.view.view_config()or registered bypyramid.config.Configurator.add_view()with arendererparameter do not require to call this function as it is auto-resolved with the submitteddata.
- class magpie.ui.utils.AdminRequests(request)[source]¶
Bases:
BaseViewsRegroups multiple administration-level operations to be dispatched to the API requests.
- create_user_default_template_data(data)[source]¶
Generates all the default values for the various fields employed for display purposes of the user creation form.
- Parameters:
data – any template data that should override the defaults.
- Returns:
updated template data with defaults and overridden values.
- get_admin_session() magpie.typedefs.CookiesType[source]¶
Temporarily login as default administrator to execute an elevated operation that the current user cannot make.
Warning
Cookies MUST NOT be preserved or memorized, to avoid user gaining restricted access. This is intended only for basic operations such as validating information. Care must be taken such information retrieved this way do not provide a way of non-administrator to indirectly infer some otherwise protected information. User sparingly.
- Returns:
Cookies of the administrator login.
- get_group_users(group_name: magpie.typedefs.Str, user_group_status: magpie.models.UserGroupStatus = UserGroupStatus.ACTIVE) List[magpie.typedefs.Str][source]¶
- update_group_info(group_name: magpie.typedefs.Str, group_info: magpie.typedefs.JSON) magpie.typedefs.JSON[source]¶
- get_user_groups(user_name: magpie.typedefs.Str, user_group_status: magpie.models.UserGroupStatus = UserGroupStatus.ACTIVE) List[magpie.typedefs.Str][source]¶
- get_user_statuses(status: magpie.typedefs.Str | int = 0) List[magpie.typedefs.Str][source]¶
Obtains all user names that have the corresponding status value.
- get_user_details(status: str | int | None = None, cookies: magpie.typedefs.CookiesType | None = None) List[magpie.typedefs.JSON][source]¶
Obtains all user details, optionally filtered to by corresponding status value.
Employ this method to avoid multiple requests fetching individual information.
- get_resource_types()[source]¶
- Returns:
dictionary of all resources as {id: ‘resource_type’}
- Return type:
dict
- static flatten_tree_resource(resource_node, resource_dict)[source]¶
- Parameters:
resource_node – any-level dictionary composing the resources tree
resource_dict – reference of flattened dictionary across levels
- Returns:
flattened dictionary resource_dict of all {id: ‘resource_type’}
- Return type:
dict
- create_user(data)[source]¶
Processes the user creation form with fields input data.
All the fields are pre- and post-validated according to expected behaviour by the API. Pre-validations attempt soft checks to detect as many potential errors such that they can all be simultaneously displayed on the form, to avoid back-and-forth erroneous submissions by the user. Post-validations are the hard checks imposed by the API, which include some of the pre-checks.
Whenever some failure occurs, returned data will contain
is_errorwithTrueorFalseaccordingly. Following successful request without error, the User will be created. It is up to the calling function to redirect the response and further process the returned data as needed.- Parameters:
data – initial templated data overrides according to who is initiation the user creation.
- Returns:
updated template data with any relevant error messages and statuses if applicable.
- Raises:
HTTPException – any unhandled or unknown HTTP error received from the API.