无法将captcha对象转换为base64

时间:2017-07-12 11:49:00

标签: python

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

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

感谢您的帮助:)

1 个答案:

答案 0 :(得分:3)

BytesIO对象转换为bytes类型:

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

这些类型不可互换,BytesIO是类文件对象,而bytes只存储str等不可变值