django_python_生成驗證時報錯TypeError: string argument expected, got 'bytes'

問題描述:

在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

發佈了157 篇原創文章 · 獲贊 45 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章