1. 添加captcha完成后,如果直接使用会报错:
报错原因:captcha 框架, 需要依赖 Pillow 这个包
在虚拟环境–安装 Python 处理图片的库 Pillow:
# 注意: 需要安装: pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
# text 文本验证码 # image 验证码图片二进制流 text, image = captcha.generate_captcha()
获取图形验证码:
uuid
—— 使用该uuid
作为key在redis中存储生成的验证码。captcha
拓展包来生成验证码图片注意,
captcha
包的使用需要提前安装依赖模块Pillow
,如下安装:
pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
编写一个demo,研究研究captcha
包的使用。
captcha
在文件夹
apps/verifications/
中新建包文件夹libs
。从上面的链接中找到
captcha
, 整体复制到libs
包中。
安装Pillow的图片库
添加captcha完成后,如果直接使用会报错:
报错原因:captcha 框架, 需要依赖 Pillow 这个包
在虚拟环境–安装 Python 处理图片的库 Pillow:
# 注意: 需要安装到虚拟环境中: pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
新建verifications
应用。
编辑verifications/views.py
注意,代码中使用
django-redis
拓展库实现redis存储,需提前安装,安装命令如下:
pip3 install django-redis
from django.shortcuts import render from django.views import View from django.http import HttpResponse from django_redis import get_redis_connection from verifications.libs.captcha.captcha import captcha # Create your views here. # 获取图形验证码 class ImageCodeView(View): def get(self, request, uuid): # 1、提取参数 # 2、校验参数 # 3、业务数据处理 # 3.1、调用captcha外部库生成图片和验证码 text, img_bytes = captcha.generate_captcha() print("验证码:", text) # 3.2、把验证码写入redis(以uuid作为key) # get_redis_connection函数:功能是获取redis链接对象,参数是一个字符串(是django缓存配置名称) # 返回值是一个redis链接对象 conn = get_redis_connection('verify_code') # setex img_37728d6c-e219-44c5-8f81-4245a9e557a4 300 KJHG conn.setex('img_%s'%uuid, 300, text) # 4、构建响应(返回图片数据) # 构造的响应体数据是图片的二进制字节数据,需要设置响应头Content-Type:image/jpeg,来 # 告诉浏览器响应体数据是图片数据,这样浏览器才能够渲染图片 return HttpResponse(img_bytes, content_type='image/jpeg')
编辑verifications/urls.py
from django.urls import re_path,path from . import views urlpatterns = [ # 在网上超过来的uuid正则表达式提取路径中的uuid # re_path(r'^image_codes/(?P<uuid>[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12})/$', views.ImageCodeView.as_view()), # 使用uuid转换器提取路径uuid值 path('image_codes/<uuid:uuid>/', views.ImageCodeView.as_view()), ]