Encode Unicode and validate Base64 text in Python
Round-trip the Korean character ๋ and reject a single stray character. Distinguish a Base64 parsing error from a Unicode decoding failure.
Convert a Python str to bytes first
b64encode expects bytes. Encode the word as UTF-8, then convert the returned Base64 bytes to an ASCII string for JSON. Sending the printed representation of a bytes object can accidentally include its b prefix and quotes in the transmitted value.
Compare valid input with one extra character
The snippet prints 64iI, ๋ and invalid Base64 in order. This field expects standard Base64 with no whitespace, so validate=True fits its contract. It prevents the inserted exclamation mark from being silently ignored.
import base64
from binascii import Error
word = "๋"
value = base64.b64encode(word.encode("utf-8")).decode("ascii")
print(value)
print(base64.b64decode(value, validate=True).decode("utf-8"))
try:
base64.b64decode("64!iI", validate=True)
except Error:
print("invalid Base64")Handle failures at the right step
A binascii.Error points to a problem parsing the encoded input. A UnicodeDecodeError from the following UTF-8 conversion means the bytes were already restored. For a file, write those bytes with Path.write_bytes. For text, confirm the original encoding before trying to display it.