Python Glossary Русский

all Python 3base64function

base64.urlsafe_b64encode()

Base64

Base64 with the URL-safe alphabet: '-' instead of '+' and '_' instead of '/'. For tokens in URLs and file names.

Syntax

base64.urlsafe_b64encode(s)

Only two characters are replaced and the '=' padding stays; it must be encoded in a query string too, so JWTs and short links often strip it with .rstrip(b'='). The decoder then has to restore the padding itself. Never read such a string with the standard b64decode: it silently drops '-' and '_'.

Examples

import base64
print(base64.urlsafe_b64encode(b'\xfb\xff'), base64.b64encode(b'\xfb\xff'))  # → b'-_8=' b'+/8='
token = base64.urlsafe_b64encode(b'hi').rstrip(b'=')
print(token)  # → b'aGk'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy