简体   繁体   English

修复Python 3.7中的base64编码错误

[英]Fixing base64 encoding error in Python 3.7

I'm trying to access an API which has requires authentication. 我正在尝试访问需要身份验证的API。 However I keep getting the error which reads " a bytes-like object is required, not 'str' " for the base64encode line. 但是,我不断收到错误,该错误为base64encode行读取“需要一个类似字节的对象,而不是'str'”。

user = input("user: example")
password = getpass.getpass("password: example1234")
authCred = base64.b64encode(user + ":" + password)

I tried to change the code to: 我试图将代码更改为:

user = input("user: example")
password = getpass.getpass("password: example1234")
authCred = base64.b64encode(user.encode('ascii') + ":" + password.encode('ascii')).decode('ascii')

But then I get the error "can't concat str to bytes" 但是然后我得到了错误“无法将str连接到字节”

Does anyone know how I can fix this? 有谁知道我该如何解决?

Your attempted fix didn't work because you tried to mix encoded and non-encoded strings. 您尝试的修复不起作用,因为您尝试混合使用编码字符串和非编码字符串。

Make a string that is the username plus a colon plus the password, then encode that whole string: 编写一个字符串,即用户名,冒号和密码,然后对整个字符串进行编码:

userpass = user + ":" + pass
authCred = base64.b64encode(userpass.encode('ascii'))

does encoding it as bytes help? 编码为字节有帮助吗?

authcred = bytes(authcred , encoding= 'utf-8') authcred =字节(authcred,encoding ='utf-8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM