python - 非常奇怪的Python 3字节到字符串失败

标签 python string python-3.x base64 byte

好吧,我希望这是一个您以前没有看到的问题。

我将代码粘贴到此处:

import binascii
import urllib.request
import urllib.parse
client_id = '2da9e3d6414047c0000000000' # a made up string
client_secret = 'fe5f334a1cf240000000000' # a made up string

url = 'https://accounts.spotify.com/api/token'
data = {'grant_type':'client_credentials'}
data = urllib.parse.urlencode(data)
login = client_id + ':' + client_secret
encoded_login = binascii.b2a_base64(login.encode('ascii'))
encoded_login = encoded_login.decode('utf-8')
print(encoded_login) ## so you know it is a string indeed

headers = {'Authorization': 'Basic ' + encoded_login}
try:
    req = urllib.request.Request(url, data.encode('ascii'), headers)
    with urllib.request.urlopen(req) as response:
        result = response.read()
except:
    raise Exception('some failure')   

我没有更改任何内容,因此每个人都可以重现该问题。现在你看到encoded_login已经成功成为一个字符串。但如果你真的运行它,你应该得到“Basic”+encoded_login 作为字节错误。

这是我得到的错误:

Invalid header value b'Basic MmRhOWUzZDY0MTQwNDdjMDAwMDAwMDAwMDpmZTVmMzM0YTFjZjI0MDAwMDAwMDAwMA==\n'

多么有趣,多么神奇!字符串 concat + 已转换为字节连接。你会重新发布这个吗?你能分享一下你的想法是什么原因吗?

谢谢

最佳答案

binascii.b2a_base64 函数在其输出中附加换行符:docs状态:

Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The newline is added because the original use case for this function was to feed it a series of 57 byte input lines to get output lines that conform to the MIME-base64 standard.

header 值中不允许使用换行符,这就是您收到错误消息的原因。该异常将 header 值报告为字节,因为 python http 客户端代码将请求转换为字节以便通过网络传输。

使用base64 module函数 - 例如 base64.b64encode - 以避免添加换行符。

关于python - 非常奇怪的Python 3字节到字符串失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35956686/

相关文章:

c++ - 将 Strncmp 与文件中的字符串一起使用

java - 想要用 "^^^"替换 "~"说 abc^^^xyz 应该像 abc~xyz 一样替换

python - 如何在不发出示例请求的情况下检查 requests.Session 是否已通过身份验证?

python - 如何通过 PyCharm 安装 PyGObject

python - 有没有办法在 Azure 服务总线上发送带有 Python 主题和订阅的文件?

python - Pandas 删除方括号和单引号

python - 比较字典的值并返回匹配值的计数

python - 连接到python的html5 websocket

c - O(n) 内对字符串指针数组进行排序的算法

Python Turtle 按住按键功能