我正在尝试找到与JavaScript中的函数“btoa”完全相同的Python等效函数,因为我想将密码编码为base64。 似乎有许多选项,如此处所列:
https://docs.python.org/3.4/library/base64.html
在Python中是否存在与“btoa”完全相同的等效函数?
我正在尝试找到与JavaScript中的函数“btoa”完全相同的Python等效函数,因为我想将密码编码为base64。 似乎有许多选项,如此处所列:
https://docs.python.org/3.4/library/base64.html
在Python中是否存在与“btoa”完全相同的等效函数?
我尝试了Python代码,并得到了以下错误(在python3下):TypeError:需要字节类似对象,而不是'str'
当我添加了编码时,它似乎可以工作。
import base64
dataString = 'Hello World!'
dataBytes = dataString.encode("utf-8")
encoded = base64.b64encode(dataBytes)
print(encoded) # res=> b'SGVsbG8gV29ybGQh'
encoded = base64.b64encode(b'Hello World!')
这行代码也是有效的。 - user3556757如果你在使用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'>
from base64 import b64encode, b64decode
def btoa(value: str) -> str:
# btoa source: https://github.com/WebKit/WebKit/blob/fcd2b898ec08eb8b922ff1a60adda7436a9e71de/Source/JavaScriptCore/jsc.cpp#L1419
binary = value.encode("latin-1")
return b64encode(binary).decode()
def atob(value: str) -> str:
binary = b64decode(value.encode())
return binary.decode("latin-1")
pip install btoa
from btoa import btoa, atob
assert btoa("Hello World!") == "SGVsbG8gV29ybGQh"
assert atob("SGVsbG8gV29ybGQh") == "Hello World!"