gws.lib.text¶
Text utilities.
Base64 encoding, data URLs (RFC 2397), indentation and line handling, and
small string conversions. Decoding errors are raised as Error.
Example:
s = gws.lib.text.to_base64('hello') # 'aGVsbG8='
gws.lib.text.from_base64(s) # b'hello'
url = gws.lib.text.to_data_url(b'<svg/>', 'image/svg+xml')
mime, content = gws.lib.text.parse_data_url(url) # ('image/svg+xml', b'<svg/>')
Source code: gws.lib.text
Package Contents¶
- gws.lib.text.dedent(text: str) str¶
Remove the common leading whitespace from all lines.
- Parameters:
text – A multiline string.
- Returns:
The dedented string. Lines that consist of whitespace only are emptied.
- gws.lib.text.from_base64(x: str | bytes, url_safe: bool = False) bytes¶
Decode a base64 string.
- Parameters:
x – A base64 string or bytes.
url_safe – Expect the URL-safe alphabet (
-and_instead of+and/).
- Returns:
The decoded bytes.
- Raises:
Error – If the input contains characters outside the alphabet or is incorrectly padded.
- gws.lib.text.parse_data_url(url: str) tuple[str, bytes]¶
Parse a data URL.
Both base64 and percent-encoded payloads are accepted. Media type parameters (e.g.
;charset=utf8) are ignored.- Parameters:
url – A
data:URL.- Returns:
A tuple of the lowercase MIME type (
text/plainif empty) and the content.- Raises:
Error – If the value is not a data URL or the payload cannot be decoded.
- gws.lib.text.to_base64(x: str | bytes, url_safe: bool = False) str¶
Encode a string or bytes as base64.
- Parameters:
x – A string, encoded as UTF-8, or bytes.
url_safe – Use the URL-safe alphabet (
-and_instead of+and/).
- Returns:
The base64 string, without line breaks.
- gws.lib.text.to_data_url(content: str | bytes, mime: gws.MimeType) str¶
Create a base64 data URL.
- Parameters:
content – Content, a string is encoded as UTF-8.
mime – MIME type of the content.
- Returns:
A
data:<mime>;base64,...URL.