ae-base 0.3.66__py3-none-any.whl → 0.3.68__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ae/base.py CHANGED
@@ -1,156 +1,221 @@
1
1
  """
2
- basic constants, helper functions and context manager
3
- =====================================================
2
+ basic constants, helper functions and context managers
3
+ ======================================================
4
4
 
5
- this module is pure python, has no external dependencies, and is providing base constants, common helper
6
- functions, useful classes and context managers.
5
+ this module is pure python, has no external dependencies, and provides a comprehensive toolkit of base constants,
6
+ common helper functions, useful classes, and context managers for a wide variety of programming tasks.
7
7
 
8
8
  .. note::
9
- on import of this module, while running on Android OS, it will monkey patch the :mod:`shutil` module
10
- to allow using them on Android devices. therefore, the import of this module should be one of the first ones
11
- in your app's main module.
9
+ on import, this module checks if it is running on the Android OS. if so, it will monkey patch the
10
+ :mod:`shutil` module to ensure functions like ``copy`` and ``move`` work correctly. to prevent
11
+ permission-related errors, this module should be one of the first imports in your Android app's main module.
12
12
 
13
13
 
14
- base constants
15
- --------------
16
-
17
- ISO format strings for ``date`` and ``datetime`` values are provided by the constants :data:`DATE_ISO` and
18
- :data:`DATE_TIME_ISO`.
14
+ string manipulation
15
+ -------------------
19
16
 
20
- the :data:`UNSET` constant is useful in cases where ``None`` is a valid data value and another special value is needed
21
- to specify that e.g., an argument or attribute has no (valid) value or did not get specified/passed.
17
+ functions for converting, cleaning, normalizing, and formatting strings.
22
18
 
23
- default values to compile file and folder names for a package or an app project are provided by the constants:
24
- :data:`DOCS_FOLDER`, :data:`TESTS_FOLDER`, :data:`TEMPLATES_FOLDER`, :data:`BUILD_CONFIG_FILE`,
25
- :data:`PACKAGE_INCLUDE_FILES_PREFIX`, :data:`PY_EXT`, :data:`PY_INIT`, :data:`PY_MAIN`, :data:`CFG_EXT`
26
- and :data:`INI_EXT`.
19
+ * :func:`camel_to_snake`: converts a string from CamelCase to snake_case.
20
+ * :func:`snake_to_camel`: converts a string from snake_case to CamelCase.
21
+ * :func:`norm_name`: normalizes a string to be a valid identifier (e.g., for variable-, method-, or file-names).
22
+ * :func:`norm_line_sep`: converts all line separator combinations (CRLF, CR) in a string to a single newline (LF).
23
+ * :func:`defuse`: converts special characters in string to Unicode alternatives, making it safe for use as
24
+ a URL slug, path or filename.
25
+ * :func:`dedefuse`: reverses the operation of :func:`defuse`, restoring the original string.
26
+ * :func:`force_encoding`: ensures text is in a specific encoding without raising errors, replacing characters as needed.
27
+ * :func:`to_ascii`: converts a Unicode string into its closest ASCII representation by removing accents and diacritics.
28
+ * :func:`ascii_str`: encodes a Unicode string into a reversible 7-bit ASCII representation, useful for transport
29
+ protocols like HTTP headers.
30
+ * :func:`str_ascii`: decodes a string created by :func:`ascii_str` back to its original Unicode form.
31
+ * :func:`format_given`: a replacement for `str.format_map` that formats a string but leaves placeholders intact if they
32
+ are not found in the provided mapping.
27
33
 
28
- with the help of the format string constant :data:`NOW_STR_FORMAT` and the function :func:`now_str` you can create a
29
- sortable and compact string from a timestamp.
30
34
 
35
+ system & environment
36
+ --------------------
31
37
 
32
- base helper functions
33
- ---------------------
38
+ inspect the operating system and manage environment variables.
34
39
 
35
- the function :func:`evaluate_literal` can be used as a replacement of :func:`ast.literal_eval` to retrieve
36
- basic data structure values from config, ini and .env files, while also accepting unquoted strings as a `str` type
37
- instance.
38
-
39
- most programming languages providing a function to determine the sign of a number. the :func:`sign` functino,
40
- provided by this module/portion is filling this gap in Python.
40
+ .. hint::
41
+ the :mod:`ae.core` portion is providing more OS-specific constants and helper functions, like e.g.
42
+ :func:`~ae.core.start_app_service` and :func:`~ae.core.request_app_permissions`.
41
43
 
42
- in order to convert and transfer Unicode character outside the 7-bit ASCII range via internet transport protocols,
43
- like http, use the helper functions :func:`ascii_str` and :func:`str_ascii`.
44
+ OS information
45
+ ~~~~~~~~~~~~~~
44
46
 
45
- :func:`now_str` creates a timestamp string with the actual UTC date and time. the :func:`utc_datetime` provides the
46
- actual UTC date and time as a datetime object.
47
+ * :data:`os_platform`: a string identifying the operating system (e.g., 'linux', 'win32', 'android', 'ios').
48
+ * :data:`os_device_id`: a string with the ID/name of the device.
49
+ * :func:`os_host_name`: determines the operating system's host/machine name.
50
+ * :func:`os_local_ip`: determines the local IP address of the machine.
51
+ * :func:`os_user_name`: determines the current logged-in user's name.
52
+ * :func:`sys_env_dict`: returns a dictionary containing key Python runtime environment values.
53
+ * :func:`sys_env_text`: compiles a formatted text block with system environment information, useful for logging.
47
54
 
48
- to write more compact and readable code for the most common file I/O operations, the helper functions :func:`read_file`
49
- and :func:`write_file` are wrapping Python's built-in :func:`open` function and its context manager.
55
+ environment variables & `.env` files
56
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
57
 
51
- the function :func:`duplicates` returns the duplicates of an iterable type.
58
+ * :func:`env_str`: retrieves the string value of an OS environment variable, with an option to automatically convert the
59
+ variable name to the conventional format.
60
+ * :func:`parse_dotenv`: parses a `.env` file and returns its key-value pairs as a dictionary.
61
+ * :func:`load_env_var_defaults`: recursively searches parent directories for `.env` files and loads any undeclared
62
+ variables.
63
+ * :func:`load_dotenvs`: detects and loads all relevant `.env` files from the current working directory and optional
64
+ also from the main module's path.
52
65
 
53
- in order to hide/mask secrets like credit card numbers, passwords or tokens in deeply nested data structures,
54
- before they get dumped e.g., to an app log file, the function :func:`mask_secrets` can be used.
55
66
 
56
- :func:`norm_line_sep` is converting any combination of line separators of a string to a single new-line character.
67
+ data structure utilities
68
+ ------------------------
57
69
 
58
- the function :func:`norm_name` converts any string into a name that can be used e.g., as a file name
59
- or as a method/attribute name.
70
+ helpers for working with lists, dictionaries, and other data structures.
60
71
 
61
- to normalize a file path, in order to remove `.`, `..` placeholders, to resolve symbolic links or to make it relative or
62
- absolute, call the function :func:`norm_path`.
72
+ * :func:`evaluate_literal`: replacement for :func:`ast.literal_eval` that also interprets/recognizes unquoted strings
73
+ as `str` type.
74
+ * :func:`duplicates`: returns a list of all duplicate items found in any type of iterable.
75
+ * :func:`deep_dict_update`: recursively updates a dictionary in-place with values from another dictionary.
76
+ * :func:`mask_secrets`: hides sensitive string values (e.g., passwords, API keys) in deeply nested data structures,
77
+ useful for logging.
63
78
 
64
- :func:`defuse` converts special characters of a URI/URL or a file path string, resulting in a string that can be used
65
- either as a URL slug or as a file name. use the function :func:`dedefuse` to convert this string back to the
66
- corresponding URL/URI or file path.
67
79
 
68
- the functions :func:`camel_to_snake` and :func:`snake_to_camel` providing name conversions of class and method names.
80
+ application & project helpers
81
+ -----------------------------
69
82
 
70
- to encode Unicode strings to other codecs, the functions :func:`force_encoding` and :func:`to_ascii` can be used.
83
+ functions to aid in application setup, configuration, and build introspection.
71
84
 
72
- the :func:`round_traditional` function gets provided by this module for traditional rounding of float values. the
73
- function signature is fully compatible with Python's :func:`round` function.
85
+ * :func:`app_name_guess`: attempts to determine the name of the currently running application from its environment.
86
+ * :func:`build_config_variable_values`: reads variable values from a `buildozer.spec` file.
87
+ * :func:`instantiate_config_parser`: returns a `ConfigParser` instance pre-configured for case-sensitive keys and
88
+ extended interpolation.
89
+ * :func:`project_main_file`: determines the absolute path to the main module file of a project package (where the
90
+ `__version__` of the app|package is defined).
91
+ * :func:`main_file_paths_parts`: returns a tuple of possible main/version file path names combinations of any project.
74
92
 
75
- the function :func:`instantiate_config_parser` ensures that the :class:`~configparser.ConfigParser` instance is
76
- correctly configured, e.g., to support case-sensitive config variable names and to use :class:`ExtendedInterpolation`
77
- as the interpolation argument.
78
93
 
79
- :func:`app_name_guess` guesses the name of o running Python application from the application environment, with the help
80
- of :func:`build_config_variable_values`, which determines config-variable-values from the build spec file of an app
81
- project.
94
+ modules and call stack inspection
95
+ ---------------------------------
82
96
 
97
+ dynamically inspect modules, execution frames, and variables on the call stack.
83
98
 
84
- operating system constants and helpers
85
- --------------------------------------
99
+ * :func:`import_module`: dynamically imports a Python module from a path without adding it to `sys.modules`.
100
+ * :func:`module_attr`: dynamically gets a reference to a module or any attribute (variable, function, class) within it.
101
+ * :func:`module_file_path`: determines the absolute file path of the module from which it is called.
102
+ * :func:`module_name`: finds the name of the first module in the call stack that is not in a predefined skip list.
103
+ * :func:`stack_frames`: a generator that yields frames from the call stack, starting at a specified depth.
104
+ * :func:`stack_var`: finds the value of a specific variable by searching up the call stack.
105
+ * :func:`stack_vars`: returns the global and local variables from a specific frame in the call stack.
106
+ * :func:`full_stack_trace`: generates a complete, detailed string representation of an exception's stack trace.
86
107
 
87
- the string :data:`os_platform` provides the OS where your app is running, extending Python's :func:`sys.platform`
88
- for mobile platforms like Android and iOS.
108
+ .. hint::
109
+ the :class:`~ae.core.AppBase` class uses these helper functions to determine the
110
+ :attr:`version <ae.core.AppBase.app_version>` and :attr:`title <ae.core.AppBase.app_title>` of an application,
111
+ if these values are not specified in the instance initializer.
89
112
 
90
- the functions :func:`os_host_name`, :func:`os_local_ip` and :func:`os_user_name` are determining machine and
91
- user information from the OS.
92
113
 
93
- use :func:`env_str` to determine the value of an OS environment variable with automatic variable name conversion. other
94
- helper functions provided by this namespace portion to determine the values of the most important system environment
95
- variables for your application are :func:`sys_env_dict` and :func:`sys_env_text`.
114
+ networking utilities
115
+ --------------------
96
116
 
97
- to integrate system environment variables from ``.env`` files into :data:`os.environ` the helper functions
98
- :func:`parse_dotenv`, :func:`load_env_var_defaults` and :func:`load_dotenvs` are provided.
117
+ * :func:`url_failure`: determines if and why a HTTP|FTP target is unavailable.
118
+ * :func:`mask_url`: hides or replaces the password/token portion of a URL for safe logging.
99
119
 
100
- the :mod:`ae.core` portion is providing more OS-specific constants and helper functions, like e.g.
101
- :func:`start_app_service` and :func:`request_app_permissions`.
102
120
 
103
- .. note::
104
- on import of this module, while running on Android OS, it will monkey patch the :mod:`shutil` module to allow
105
- using them on Android devices, and on the first app start requesting the permissions of your app. therefore, to
106
- prevent permission errors, the import of this module should be the first statement in the main module of your app.
121
+ general utilities & helpers
122
+ ---------------------------
107
123
 
124
+ a collection of miscellaneous mathematical, date/time, and other standalone helper functions.
108
125
 
109
- types, classes and mixins
110
- -------------------------
126
+ mathematical
127
+ ~~~~~~~~~~~~
111
128
 
112
- the :class:`UnsetType` class can be used e.g., for the declaration of optional function and method parameters,
113
- allowing also ``None`` is an accepted argument value.
129
+ * :func:`sign`: returns the sign of a number (-1 for negative, 0 for zero, 1 for positive).
130
+ * :func:`round_traditional`: rounds a float value using traditional rounding rules (e.g., `0.5` rounds up).
114
131
 
115
- to extend any class with an intelligent error message handling, add the mixin :class:`ErrorMsgMixin` to it.
132
+ date & time
133
+ ~~~~~~~~~~~
134
+ * :func:`utc_datetime`: Returns the current date and time as a timezone-naive `datetime` object in UTC.
135
+ * :func:`now_str`: creates a compact, sortable timestamp string from the current UTC time.
116
136
 
117
- the classes :class:`UnformattedValue` and :class:`GivenFormatter` can be used to format strings with placeholders
118
- enclosed in curly brackets. the function :func:`format_given` is using them to format templates with placeholders.
137
+ miscellaneous
138
+ ~~~~~~~~~~~~~
139
+ * :func:`dummy_function`: a null function that accepts any arguments and returns `None`.
119
140
 
120
141
 
121
- generic context manager
142
+ types, classes & mixins
122
143
  -----------------------
123
144
 
124
- the context manager :func:`in_wd` allows switching the current working directory temporarily. the following
125
- example demonstrates a typical usage, together with a temporary path, created with the help of Pythons
126
- :class:`~tempfile.TemporaryDirectory` class::
127
-
128
- with tempfile.TemporaryDirectory() as tmp_dir, in_wd(tmp_dir):
129
- # within the context the tmp_dir is set as the current working directory
130
- assert os.getcwd() == tmp_dir
131
- # current working directory set back to the original path and the temporary directory got removed
132
-
133
-
134
- call stack inspection
135
- ---------------------
145
+ * :class:`UnsetType`: the class for the :data:`UNSET` singleton object, useful as a sentinel value when `None` is a
146
+ valid input.
147
+ * :class:`ErrorMsgMixin`: a mixin class that provides any class with a sophisticated error message handling and
148
+ logging property.
149
+ * :class:`UnformattedValue`: a helper class for :func:`format_given` to represent a placeholder that was not found in
150
+ the formatting map.
151
+ * :class:`GivenFormatter`: a helper class for :func:`format_given` that overrides default formatting behavior to keep
152
+ missing placeholders.
136
153
 
137
- :func:`module_attr` dynamically determines a reference to an attribute (variable, function, class, ...) in a module.
138
154
 
139
- :func:`module_name`, :func:`stack_frames`, :func:`stack_var` and :func:`stack_vars` are inspecting the call stack frames
140
- to determine e.g., variable values of the callers of a function/method.
141
-
142
- .. hint::
143
- the :class:`AppBase` class uses these helper functions to determine the :attr:`version <AppBase.app_version>` and
144
- :attr:`title <AppBase.app_title>` of an application, if these values are not specified in the instance initializer.
145
-
146
- another useful helper function provided by this portion to inspect and debug your code is :func:`full_stack_trace`.
155
+ base constants
156
+ --------------
147
157
 
158
+ predefined constants for project structure, file conventions, and default settings.
159
+
160
+ project & file structure
161
+ ~~~~~~~~~~~~~~~~~~~~~~~~
162
+
163
+ * :data:`DOCS_FOLDER`: default name for a project's documentation folder ('docs').
164
+ * :data:`TESTS_FOLDER`: default name for a project's tests folder ('tests').
165
+ * :data:`TEMPLATES_FOLDER`: default name for a folder containing file templates ('templates').
166
+ * :data:`BUILD_CONFIG_FILE`: default name for a build configuration file ('buildozer.spec').
167
+ * :data:`DEF_PROJECT_PARENT_FOLDER`: default directory name for grouping source code projects ('src').
168
+ * :data:`PY_CACHE_FOLDER`: default name for Python's cache folder ('__pycache__').
169
+ * :data:`PY_EXT`: file extension for Python modules ('.py').
170
+ * :data:`PY_INIT`: the filename for a Python package initializer ('__init__.py').
171
+ * :data:`PY_MAIN`: the filename for a Python executable's main module ('__main__.py').
172
+ * :data:`CFG_EXT`: file extension for CFG configuration files ('.cfg').
173
+ * :data:`INI_EXT`: file extension for INI configuration files ('.ini').
174
+ * :data:`DOTENV_FILE_NAME`: default name for environment variable files ('.env').
175
+ * :data:`PACKAGE_INCLUDE_FILES_PREFIX`: prefix for files/folders to be included in setup package data (used by
176
+ :mod:`ae.updater` and :mod:`aedev.project_manager`)
177
+
178
+ formats & default settings
179
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
180
+
181
+ * :data:`DATE_ISO`: ISO format string for dates ("%Y-%m-%d").
182
+ * :data:`DATE_TIME_ISO`: ISO format string for :mod:`datetime.datetime` dates ("%Y-%m-%d %H:%M:%S.%f").
183
+ * :data:`NOW_STR_FORMAT`: the datetime format string, used e.g. by :func:`now_str` for creating timestamps.
184
+ * :data:`NAME_PARTS_SEP`: the character used as a separator in name conversions ('_').
185
+ * :data:`DEF_ENCODING`: the default encoding used for string operations ('ascii').
186
+ * :data:`DEF_ENCODE_ERRORS`: the default error handling strategy for encoding ('backslashreplace').
187
+ * :data:`SKIPPED_MODULES`: a tuple of module names to be ignored by stack inspection functions.
188
+ * :data:`UNSET`: a singleton instance of :class:`UnsetType`, used where `None` is a valid data value.
189
+
190
+
191
+ file, path & I/O operations
192
+ ---------------------------
193
+
194
+ simplify file system interactions with wrappers and context managers.
195
+
196
+ * :func:`read_file`: reads the entire content of a text or binary file into a string or bytes object.
197
+ * :func:`write_file`: writes a string or bytes object to a file, overwriting existing content.
198
+ * :func:`norm_path`: normalizes a path by expanding user home directories (`~`), resolving `.`, `..`, symbolic links,
199
+ and converting between absolute and relative paths.
200
+ * :func:`in_wd`: a context manager that temporarily switches the current working directory.
148
201
 
149
202
  os.path shortcuts
150
- -----------------
151
-
152
- the following data items are pointers to shortcut at runtime the lookup to their related functions in the
153
- Python module :mod:`os.path`:
203
+ ~~~~~~~~~~~~~~~~~
204
+
205
+ the following are direct references to functions in the :mod:`os.path` module for convenient and quicker access:
206
+
207
+ * :data:`os_path_abspath`: :func:`os.path.abspath`
208
+ * :data:`os_path_basename`: :func:`os.path.basename`
209
+ * :data:`os_path_dirname`: :func:`os.path.dirname`
210
+ * :data:`os_path_expanduser`: :func:`os.path.expanduser`
211
+ * :data:`os_path_isdir`: :func:`os.path.isdir`
212
+ * :data:`os_path_isfile`: :func:`os.path.isfile`
213
+ * :data:`os_path_join`: :func:`os.path.join`
214
+ * :data:`os_path_normpath`: :func:`os.path.normpath`
215
+ * :data:`os_path_realpath`: :func:`os.path.realpath`
216
+ * :data:`os_path_relpath`: :func:`os.path.relpath`
217
+ * :data:`os_path_sep`: :data:`os.path.sep`
218
+ * :data:`os_path_splitext`: :func:`os.path.splitext`
154
219
  """
155
220
  # pylint: disable=too-many-lines
156
221
  import datetime
@@ -162,6 +227,7 @@ import platform
162
227
  import re
163
228
  import shutil
164
229
  import socket
230
+ import ssl
165
231
  import string
166
232
  import sys
167
233
  import unicodedata
@@ -172,11 +238,14 @@ from configparser import ConfigParser, ExtendedInterpolation
172
238
  from contextlib import contextmanager
173
239
  from importlib.machinery import ModuleSpec
174
240
  from inspect import getinnerframes, getouterframes, getsourcefile
241
+ from urllib.error import HTTPError, URLError
242
+ from urllib.parse import urlparse, urlunparse
243
+ from urllib.request import urlopen
175
244
  from types import ModuleType
176
245
  from typing import Any, Callable, Generator, Iterable, MutableMapping, Optional, Union, cast
177
246
 
178
247
 
179
- __version__ = '0.3.66'
248
+ __version__ = '0.3.68'
180
249
 
181
250
 
182
251
  os_path_abspath = os.path.abspath
@@ -359,7 +428,6 @@ def deep_dict_update(data: dict, update: dict, overwrite: bool = True):
359
428
  data[upd_key] = upd_val
360
429
 
361
430
 
362
- URI_SEP_CHAR = '⫻' # U+2AFB: TRIPLE SOLIDUS BINARY RELATION
363
431
  # noinspection GrazieInspection
364
432
  ASCII_UNICODE = (
365
433
  ('/', '⁄'), # U+2044: Fraction Slash; '∕' U+2215: Division Slash; '⧸' U+29F8: Big Solidus;
@@ -397,13 +465,19 @@ ASCII_UNICODE = (
397
465
  # ' ' U+202F: Narrow No-Break Space (NNBSP); ' ' U+205F Medium Mathematical Space;
398
466
  # '␠' U+2420 symbol for space; '␣' U+2423 Open Box; ' ' U+3000: Ideographic Space
399
467
  (chr(127), '␡'), # U+2421: DELETE SYMBOL
400
- # ('_', '𛲖'), # U+1BC96: Duployan Affix Low Line; '_' U+FF3F Fullwidth Low Line
401
- )
402
- """ transformation table of special ASCII to Unicode alternative character,
468
+ # ('_', '𛲖'), # U+1BC96: Duployan Affix Low Line; '_' U+FF3F Fullwidth Low Line
469
+ ) + tuple((chr(low_asc_ord), chr(0x2400 + low_asc_ord)) for low_asc_ord in range(32))
470
+ """ transformation table of special ASCII characters to a similar/alternative non-functional/-escaping Unicode char,
403
471
  see https://www.compart.com/en/unicode/category/Po and https://xahlee.info/comp/unicode_naming_slash.html (http!) """
404
472
 
405
- ASCII_TO_UNICODE = dict(ASCII_UNICODE) #: map to convert ASCII to an alternative defused Unicode character
406
- UNICODE_TO_ASCII = {unicode_char: ascii_char for ascii_char, unicode_char in ASCII_UNICODE} #: Unicode to ASCII map
473
+ URI_SEP_STR = '://' #: separator between service and address(host/path) in URIs
474
+ URI_SEP_UNICODE_CHAR = '⫻' #: single Unicode char for :data:`URI_SEP_STR` U+2AFB: TRIPLE SOLIDUS BINARY RELATION
475
+
476
+ ASCII_TO_UNICODE = str.maketrans(dict(ASCII_UNICODE))
477
+ """ :func:`str.translate` map to convert ASCII to an alternative defused Unicode character - used by :func:`defuse` """
478
+ UNICODE_TO_ASCII = str.maketrans({unicode_char: ascii_char for ascii_char, unicode_char in
479
+ ASCII_UNICODE + ((URI_SEP_STR, URI_SEP_UNICODE_CHAR), )})
480
+ """ :func:`str.translate` Unicode to ASCII map - used by :func:`dedefuse` """
407
481
 
408
482
 
409
483
  def dedefuse(value: str) -> str:
@@ -412,15 +486,7 @@ def dedefuse(value: str) -> str:
412
486
  :param value: string defused with the function :func:`defuse`.
413
487
  :return: re-activated form of the string (with all ASCII special characters recovered).
414
488
  """
415
- original = ""
416
- for char in value:
417
- if char in UNICODE_TO_ASCII:
418
- char = UNICODE_TO_ASCII[char]
419
- elif 0x2400 <= (code := ord(char)) <= 0x241F:
420
- char = chr(code - 0x2400)
421
- original += char
422
-
423
- return original.replace(URI_SEP_CHAR, '://')
489
+ return value.translate(UNICODE_TO_ASCII)
424
490
 
425
491
 
426
492
  def defuse(value: str) -> str:
@@ -446,15 +512,7 @@ def defuse(value: str) -> str:
446
512
  .. hint:: use the :func:`dedefuse` function to convert the defused string back to the corresponding URI/file-path.
447
513
 
448
514
  """
449
- defused = ""
450
- value = value.replace('://', URI_SEP_CHAR) # make URIs shorter
451
- for char in value:
452
- if char in ASCII_TO_UNICODE:
453
- char = ASCII_TO_UNICODE[char]
454
- elif (code := ord(char)) <= 31:
455
- char = chr(0x2400 + code)
456
- defused += char
457
- return defused
515
+ return value.replace(URI_SEP_STR, URI_SEP_UNICODE_CHAR).translate(ASCII_TO_UNICODE) # replace makes URIs shorter
458
516
 
459
517
 
460
518
  def dummy_function(*_args, **_kwargs):
@@ -500,13 +558,14 @@ def env_str(name: str, convert_name: bool = False) -> Optional[str]:
500
558
  return os.environ.get(name)
501
559
 
502
560
 
503
- def evaluate_literal(literal_string: str) -> Any:
561
+ def evaluate_literal(literal_string: str
562
+ ) -> Optional[Union[bool, bytes, dict, complex, float, int, list, set, str, tuple]]:
504
563
  """ evaluates a Python expression while accepting unquoted strings as str type.
505
564
 
506
565
  :param literal_string: any literal of the base types (like dict, list, set, tuple) which are recognized
507
566
  by :func:`ast.literal_eval`.
508
- :return: an instance of the data type or the specified string, even if it is not quoted with
509
- high comma characters.
567
+ :return: an instance of the data type or the specified string, even if it is not quoted with high
568
+ comma characters. `None` will be returned if the specified literal is the string "None".
510
569
  """
511
570
  try:
512
571
  return literal_eval(literal_string)
@@ -623,7 +682,11 @@ def import_module(import_name: str, path: Optional[Union[str, UnsetType]] = UNSE
623
682
 
624
683
 
625
684
  def instantiate_config_parser() -> ConfigParser:
626
- """ instantiate and prepare config file parser. """
685
+ """ instantiate and prepare config file parser.
686
+
687
+ ensures that the :class:`~configparser.ConfigParser` instance is correctly configured, e.g., to support
688
+ case-sensitive config variable names and to use :class:`ExtendedInterpolation` as the interpolation argument.
689
+ """
627
690
  cfg_parser = ConfigParser(allow_no_value=True, interpolation=ExtendedInterpolation())
628
691
  # set optionxform to have case-sensitive var names (or use 'lambda option: option')
629
692
  # mypy V 0.740 bug - see mypy issue #5062: adding pragma "type: ignore" breaks PyCharm (showing
@@ -640,6 +703,15 @@ def in_wd(new_cwd: str) -> Generator[None, None, None]:
640
703
 
641
704
  :param new_cwd: path to the directory to switch to (within the context/with block).
642
705
  an empty string gets interpreted as the current working directory.
706
+
707
+ the following example demonstrates a typical usage, together with a temporary path, created with the help of Pythons
708
+ :class:`~tempfile.TemporaryDirectory` class::
709
+
710
+ with tempfile.TemporaryDirectory() as tmp_dir, in_wd(tmp_dir):
711
+ # within the context the tmp_dir is set as the current working directory
712
+ assert os.getcwd() == tmp_dir
713
+ # here the current working directory got set back to the original path and the temporary directory got removed
714
+
643
715
  """
644
716
  cur_dir = os.getcwd()
645
717
  try:
@@ -744,6 +816,22 @@ def mask_secrets(data: Union[dict, Iterable], fragments: Iterable[str] = ('passw
744
816
  return data
745
817
 
746
818
 
819
+ def mask_url(url: str, replacement: str = "¿¿¿") -> str:
820
+ """ hide|replace the password/token in a URL.
821
+
822
+ :param url: URL in which an optional password|token will be searched and replaced.
823
+ :param replacement: optional replacement string, if not specified then the default value will be used.
824
+ :return: URL with the credentials masked/replaced.
825
+ """
826
+ parts = urlparse(url)
827
+ if parts.password is None:
828
+ return url
829
+ # manually split out the netloc, because using parts.hostname/,port would have to be checked for None&hostname.lower
830
+ parts = parts._replace(netloc=f"{parts.username}:{replacement}@{parts.netloc.rpartition('@')[-1]}")
831
+ # noinspection PyTypeChecker
832
+ return urlunparse(parts)
833
+
834
+
747
835
  def module_attr(import_name: str, attr_name: str = "") -> Optional[Any]:
748
836
  """ determine dynamically a reference to a module or to any attribute (variable/func/class) declared in the module.
749
837
 
@@ -920,7 +1008,8 @@ def os_local_ip() -> str:
920
1008
  def _os_platform() -> str:
921
1009
  """ determine the operating system where this code is running (used to initialize the :data:`os_platform` variable).
922
1010
 
923
- :return: operating system (extension) as string:
1011
+ :return: operating system (extension) as string. extending Python's :func:`sys.platform`
1012
+ for mobile platforms like Android and iOS:
924
1013
 
925
1014
  * `'android'` for all Android systems.
926
1015
  * `'cygwin'` for MS Windows with an installed Cygwin extension.
@@ -940,7 +1029,7 @@ os_platform = _os_platform()
940
1029
  """ operating system / platform string (see :func:`_os_platform`).
941
1030
 
942
1031
  this string value gets determined for most of the operating systems with the help of Python's :func:`sys.platform`
943
- function and additionally detects the operating systems iOS and Android (not supported by Python).
1032
+ function and additionally detects the operating systems iOS and Android (currently not fully supported by Python).
944
1033
  """
945
1034
 
946
1035
 
@@ -1227,6 +1316,38 @@ def to_ascii(unicode_str: str) -> str:
1227
1316
  return "".join([c for c in nfkd_form if not unicodedata.combining(c)]).replace('ß', "ss").replace('€', "Euro")
1228
1317
 
1229
1318
 
1319
+ def url_failure(url: str, timeout: Optional[float] = None) -> str: # pylint: disable=too-many-return-statements
1320
+ """ determine if and why an FTP or HTTP[S] target is not available via a GET request.
1321
+
1322
+ :param url: URL of an target|page|file to check (not downloaded, fetching only the header).
1323
+ :param timeout: connection timeout in seconds (see :func:`urllib.request.urlopen`).
1324
+ :return: empty string if target header is available, else an error description. if an
1325
+ FTP|HTTP response error occurred then the error/status code
1326
+ will be returned in the first 3 characters.
1327
+ """
1328
+ # noinspection PyBroadException
1329
+ try:
1330
+ with urlopen(url, timeout=timeout) as response: # open connection and read header
1331
+ status = response.getcode() # no need to call response.read()
1332
+ return "" if 200 <= status < 300 else f"{status} {mask_url(url)} {response.reason=}"
1333
+
1334
+ except HTTPError as exception:
1335
+ return f"{exception.code} {mask_url(url)} raised HTTPError {exception.reason=}"
1336
+
1337
+ except URLError as exception:
1338
+ err_prefix = f"996 {mask_url(url)} raised {exception.errno=} {exception.reason=};"
1339
+ if isinstance(exception.reason, socket.gaierror):
1340
+ return f"{err_prefix} could not resolve hostname"
1341
+ if isinstance(exception.reason, socket.timeout):
1342
+ return f"{err_prefix} connection timed out after {timeout} seconds"
1343
+ if isinstance(exception.reason, ssl.SSLCertVerificationError):
1344
+ return f"{err_prefix} SSL certificate verification failed"
1345
+ return f"{err_prefix} could not reach the server"
1346
+
1347
+ except Exception: # pylint: disable=broad-exception-caught
1348
+ return f"999 {mask_url(url)} raised unexpected exception" # NOT put str(_exception) because contains password
1349
+
1350
+
1230
1351
  def utc_datetime() -> datetime.datetime:
1231
1352
  """ return the current UTC timestamp as string (to use as suffix for file and variable/attribute names).
1232
1353
 
@@ -1328,14 +1449,14 @@ class ErrorMsgMixin: # pylint: di
1328
1449
  os_device_id = os_host_name()
1329
1450
  """ user-definable id/name of the device, defaults to os_host_name() on most platforms, alternatives are:
1330
1451
 
1331
- on all platforms:
1332
- - socket.gethostname()
1333
1452
  on Android (check with adb shell 'settings get global device_name' and adb shell 'settings list global'):
1334
1453
  - Settings.Global.DEVICE_NAME (Settings.Global.getString(context.getContentResolver(), "device_name"))
1335
1454
  - android.os.Build.DEVICE/.MANUFACTURER/.BRAND/.HOST
1336
1455
  - DeviceName.getDeviceName()
1337
1456
  on MS Windows:
1338
1457
  - os.environ['COMPUTERNAME']
1458
+ on all other platforms:
1459
+ - socket.gethostname()
1339
1460
  """
1340
1461
  if os_platform == 'android': # pragma: no cover
1341
1462
  # determine Android device id because os_host_name() returns mostly 'localhost' and not the user-definable device id
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ae_base
3
- Version: 0.3.66
4
- Summary: ae namespace module portion base: basic constants, helper functions and context manager
3
+ Version: 0.3.68
4
+ Summary: ae namespace module portion base: basic constants, helper functions and context managers
5
5
  Home-page: https://gitlab.com/ae-group/ae_base
6
6
  Author: AndiEcker
7
7
  Author-email: aecker2@gmail.com
@@ -36,8 +36,6 @@ Requires-Dist: pytest-cov; extra == "dev"
36
36
  Requires-Dist: pytest-django; extra == "dev"
37
37
  Requires-Dist: typing; extra == "dev"
38
38
  Requires-Dist: types-setuptools; extra == "dev"
39
- Requires-Dist: wheel; extra == "dev"
40
- Requires-Dist: twine; extra == "dev"
41
39
  Provides-Extra: docs
42
40
  Provides-Extra: tests
43
41
  Requires-Dist: anybadge; extra == "tests"
@@ -51,8 +49,6 @@ Requires-Dist: pytest-cov; extra == "tests"
51
49
  Requires-Dist: pytest-django; extra == "tests"
52
50
  Requires-Dist: typing; extra == "tests"
53
51
  Requires-Dist: types-setuptools; extra == "tests"
54
- Requires-Dist: wheel; extra == "tests"
55
- Requires-Dist: twine; extra == "tests"
56
52
  Dynamic: author
57
53
  Dynamic: author-email
58
54
  Dynamic: classifier
@@ -69,17 +65,17 @@ Dynamic: summary
69
65
 
70
66
  <!-- THIS FILE IS EXCLUSIVELY MAINTAINED by the project ae.ae v0.3.96 -->
71
67
  <!-- THIS FILE IS EXCLUSIVELY MAINTAINED by the project aedev.tpl_namespace_root V0.3.14 -->
72
- # base 0.3.66
68
+ # base 0.3.68
73
69
 
74
70
  [![GitLab develop](https://img.shields.io/gitlab/pipeline/ae-group/ae_base/develop?logo=python)](
75
71
  https://gitlab.com/ae-group/ae_base)
76
72
  [![LatestPyPIrelease](
77
- https://img.shields.io/gitlab/pipeline/ae-group/ae_base/release0.3.65?logo=python)](
78
- https://gitlab.com/ae-group/ae_base/-/tree/release0.3.65)
73
+ https://img.shields.io/gitlab/pipeline/ae-group/ae_base/release0.3.67?logo=python)](
74
+ https://gitlab.com/ae-group/ae_base/-/tree/release0.3.67)
79
75
  [![PyPIVersions](https://img.shields.io/pypi/v/ae_base)](
80
76
  https://pypi.org/project/ae-base/#history)
81
77
 
82
- >ae namespace module portion base: basic constants, helper functions and context manager.
78
+ >ae namespace module portion base: basic constants, helper functions and context managers.
83
79
 
84
80
  [![Coverage](https://ae-group.gitlab.io/ae_base/coverage.svg)](
85
81
  https://ae-group.gitlab.io/ae_base/coverage/index.html)
@@ -0,0 +1,7 @@
1
+ ae/base.py,sha256=B4qkfPNmuDeyFCLY7t2QbDtCv2uFpE8novuc8UTgh7M,77075
2
+ ae_base-0.3.68.dist-info/licenses/LICENSE.md,sha256=K2nZMCD-VuxJiIVGUFsN_TSl68W3biSTBew0_9jOUXc,35003
3
+ ae_base-0.3.68.dist-info/METADATA,sha256=kQkdHTEjrkMJJgBCyls3hAJL4w2OKOagFbZf3V7sK2A,5469
4
+ ae_base-0.3.68.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ ae_base-0.3.68.dist-info/top_level.txt,sha256=vUdgAslSmhZLXWU48fm8AG2BjVnkOWLco8rzuW-5zY0,3
6
+ ae_base-0.3.68.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ ae_base-0.3.68.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
- <!-- THIS FILE IS EXCLUSIVELY MAINTAINED by the project aedev.project_tpls v0.3.46 -->
1
+ <!-- THIS FILE IS EXCLUSIVELY MAINTAINED by the project aedev.project_tpls v0.3.55 -->
2
2
  ### GNU GENERAL PUBLIC LICENSE
3
3
 
4
4
  Version 3, 29 June 2007
@@ -1,7 +0,0 @@
1
- ae/base.py,sha256=JHqqxdP33QB7BI5NfLKBTF1QU2o_DIpIId9VQv8UKYs,69668
2
- ae_base-0.3.66.dist-info/licenses/LICENSE.md,sha256=tgCt6xhP3pM6OcWOWsCTUNed3CEhLTOaRgBMUMynA0I,35003
3
- ae_base-0.3.66.dist-info/METADATA,sha256=iDIXXfhbEK4B89iEK3tOqf8INLUpauy6WJvYeqzEMJs,5619
4
- ae_base-0.3.66.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
- ae_base-0.3.66.dist-info/top_level.txt,sha256=vUdgAslSmhZLXWU48fm8AG2BjVnkOWLco8rzuW-5zY0,3
6
- ae_base-0.3.66.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
- ae_base-0.3.66.dist-info/RECORD,,