Python base64 urlsafe_b64encode














































Python base64 urlsafe_b64encode



Python base64 URLSAFE_b64Encode METHOD

Urlsafe_b64encode method is a part of python's Lib/base64.py module. This module provides functionality for encoding binary data to printable ASCII characters and decoding such encodings back to binary, read more about the module here.There are two interfaces provided by this module. Urlsafe_b64encode method is a part of modern interface. The modern interface supports encoding bytes-like objects to ASCII bytes, and decoding bytes-like objects or strings containing ASCII to bytes.

urlsafe_b64encode(s)

Arguments

s = Bytes-like object or byte string

Description

This method encodes the bytes-like object provided in the argument s having binary data, and returns the bytes containing the base64 encoded data. The characters used are URL - and filesystem-safe alphabets, which means the character '+' is substituted with '-' and '/' is substituted with '_' in the standard Base64 alphabet. The encoded string can still have '=' character.
The urlsafe_b64encode( ) method uses b64encode method to return the encoded bytes object. In the official documents it is implemented as
_urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_')
def
urlsafe_b64encode(s):
return b64encode(s).translate(_urlsafe_encode_translation)

Limitations

  • Input arguments should be a byte like object or a byte string

Usage

>>> import base64

>>> byte_string = b"<<??String to be encoded??>>"
>>>
print
(base64.urlsafe_b64encode(byte_string))
b'PDw_P1N0cmluZyB0byBiZSBlbmNvZGVkPz8-Pg=='

Note

If a string is used instead of a byte string the following error will occur
TypeError: expected bytes-like object, not str
If no input is provided as an argument the following error will occur
TypeError: urlsafe_b64encode() missing 1 required positional argument: 's'

Comments