我目前正在使用python3,我的项目需要验证码生成。我的目标是生成验证码然后将其作为base64返回,以便它可以通过JSON提供给客户端。
但是我无法将其转换为base64字符串:
captcha=image.generate(captchatext)
assert isinstance(captcha, BytesIO)
captcha=base64.b64encode(captcha)
返回错误:
captcha=base64.b64encode(captcha)
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not '_io.BytesIO'
我不完全确定为什么?有人可以帮助我理解为什么它不会转换?
感谢您的帮助:)
答案 0 :(得分:3)
将BytesIO
对象转换为bytes
类型:
captcha = base64.b64encode(image.generate(captchatext).getvalue())
这些类型不可互换,BytesIO
是类文件对象,而bytes
只存储str
等不可变值