python 是否等同于 Javascript 的 'btoa'

Does python have an equivalent to Javascript's 'btoa'

我正在尝试找到与 javascript 的函数 'btoa' 完全等价的函数,因为我想将密码编码为 base64。然而,似乎有很多选择,如下所列:

https://docs.python.org/3.4/library/base64.html

python 中是否有与 'btoa' 完全相同的词?

Python的Base64:

import base64

encoded = base64.b64encode(b'Hello World!')
print(encoded)

# value of encoded is SGVsbG8gV29ybGQh

Javascript的btoa:

var str = "Hello World!";
var enc = window.btoa(str);

var res = enc;

// value of res is SGVsbG8gV29ybGQh

如您所见,它们都产生相同的结果。

我尝试了 python 代码并获得了(python3) TypeError: a bytes-like object is required, not 'str'

当我添加编码时,它似乎起作用了

import base64

dataString = 'Hello World!'
dataBytes = dataString.encode("utf-8")
encoded = base64.b64encode(dataBytes)

print(encoded)  # res=> b'SGVsbG8gV29ybGQh'

如果你在 django 中,通常对类型有点棘手。

import json
import base64


data = [{"a": 1, "b": 2}]

btoa = lambda x:base64.b64decode(x)
atob = lambda x:base64.b64encode(bytes(x, 'utf-8')).decode('utf-8')

encoded = atob(json.dumps(data))
print(encoded)
# W3siYSI6IDEsICJiIjogMn1d
print(type(encoded))
# <class 'str'>

decoded = json.loads(btoa(encoded))
print(decoded)
# [{'a': 1, 'b': 2}]
print(type(decoded))
# <class 'list'>