无法将验证码对象转换为base64



我目前正在使用 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'

我不完全确定为什么? 有人可以帮助我理解为什么它不会转换吗?

感谢您的任何帮助:)

BytesIO对象转换为bytes类型:

captcha = base64.b64encode(image.generate(captchatext).getvalue())

这些类型不可互换,BytesIO是一个类似文件的对象,bytes只是存储不可变的值,如str

最新更新