encodings#
This module contains basic methods for base64 encoding and decoding. It also contains a handy dictionary of MIME headers for several commong file types.
b64_encode#
- pocketwelt.encodings.b64_encode(obj: Any, type_or_header: str) str#
Encode an object to a base64 string with a MIME header.
- Parameters:
obj (Any) – The object to encode. Can be a string (file path or content), BytesIO, StringIO, bytes, or any other object that can be converted to bytes. If obj does not support casting to bytes, will raise its own exception.
type_or_header (str) – Either a key from MIME_HEADERS or a full MIME header.
- Raises:
ValueError – If the provided type_or_header is not supported or invalid.
- Returns:
A string in the format “data:<mime_header>;base64,<encoded_data>”.
- Return type:
str
Examples
>>> b64_encode("hello.txt", "text") 'data:text/plain;base64,aGVsbG8udHh0'
>>> b64_encode(b"binary data", "application/octet-stream") 'data:application/octet-stream;base64,YmluYXJ5IGRhdGE='
b64_decode#
- pocketwelt.encodings.b64_decode(encoded_obj: str, filepath: str | None = None) str | BytesIO#
Decode a base64 encoded string.
- Parameters:
encoded_obj (str) – The base64 encoded string to decode.
filepath (str, optional) – The path to save the decoded content as a file. If None, the decoded content is returned as a BytesIO object. Defaults to None.
- Raises:
FileExistsError – If the specified file path already exists.
- Returns:
- If fileobj is a valid path, returns the absolute path of the
created file as a string. If fileobj is None, returns a BytesIO object containing the decoded content.
- Return type:
Union[str, BytesIO]
Examples
>>> decoded = b64_decode("data:text/plain;base64,aGVsbG8=") >>> decoded.getvalue() b'hello'
>>> file_path = b64_decode("data:text/plain;base64,aGVsbG8=", "output.txt") >>> with open(file_path, "r") as f: ... print(f.read()) hello
MIME_HEADERS#
To access this variable simply import it from the module:
from pocektwelt.encodings import MIME_HEADERS