django_python_生成验证时报错TypeError: string argument expected, got 'bytes'

耗尽温柔 提交于 2020-01-22 08:43:02

问题描述:

在django的views.py视图中定义视图函数生成二维码并返回给网页,生成验证码过程中发生错误,如下:

TypeError: string argument expected, got 'bytes'
Traceback (most recent call last):
  File "G:\anaconda\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "F:\django_lear\project2\myApp\views.py", line 73, in verifycode
    im.save(buf, 'png')
  File "G:\anaconda\lib\site-packages\PIL\Image.py", line 1930, in save
    save_handler(self, fp, filename)
  File "G:\anaconda\lib\site-packages\PIL\PngImagePlugin.py", line 731, in _save
    fp.write(_MAGIC)
TypeError: string argument expected, got 'bytes'
[01/Jan/2020 14:32:25] "GET /myApp/verifycode/ HTTP/1.1" 500 77810
F:\django_lear\project2\myApp\views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 01, 2020 - 14:35:57
Django version 2.2.6, using settings 'project2.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /myApp/verifycode/
Traceback (most recent call last):
  File "G:\anaconda\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "F:\django_lear\project2\myApp\views.py", line 73, in verifycode
    im.save(buf, 'png')
  File "G:\anaconda\lib\site-packages\PIL\Image.py", line 1930, in save
    save_handler(self, fp, filename)
  File "G:\anaconda\lib\site-packages\PIL\PngImagePlugin.py", line 731, in _save
    fp.write(_MAGIC)
TypeError: string argument expected, got 'bytes'
[01/Jan/2020 14:36:06] "GET /myApp/verifycode/ HTTP/1.1" 500 77808
F:\django_lear\project2\myApp\views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
January 01, 2020 - 14:36:41
Django version 2.2.6, using settings 'project2.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /myApp/verifycode/
Traceback (most recent call last):
  File "G:\anaconda\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "G:\anaconda\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "F:\django_lear\project2\myApp\views.py", line 73, in verifycode
    im.save(buf, 'png')
  File "G:\anaconda\lib\site-packages\PIL\Image.py", line 1930, in save
    save_handler(self, fp, filename)
  File "G:\anaconda\lib\site-packages\PIL\PngImagePlugin.py", line 731, in _save
    fp.write(_MAGIC)
TypeError: string argument expected, got 'bytes'

生成验证码的代码如下:

# 验证码
def verifycode(request):
    # 引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    font = ImageFont.truetype(r'C:/windows/fonts/himalaya.ttf', 23)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    import io
    buf = io.StringIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

原因分析:

分析了很久没没找到原因,不过解决方案已经知道

解决方案:

用BytesIO替代StringIO即可解决问题

修改后代码:

# 验证码
def verifycode(request):
    # 引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    font = ImageFont.truetype(r'C:/windows/fonts/himalaya.ttf', 23)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    # 内存文件操作
    import io
    # buf = io.StringIO()
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

感谢:

https://blog.csdn.net/mr_oldcold/article/details/91217261

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!