【python】django中图形验证码
作者:互联网
生成验证码图片的第三方包–captcha
一、准备 captcha 扩展包
- 我们生成图形验证码, 需要借助外部框架: captcha.
这里有大牛的captcha包
二、安装Pillow的图片库
1. 添加captcha完成后,如果直接使用会报错:
-
报错原因:captcha 框架, 需要依赖 Pillow 这个包
-
在虚拟环境–安装 Python 处理图片的库 Pillow:
# 注意: 需要安装:
pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
三、captcha 的使用
- captcha 这个框架中有一个 generate_captcha( ) 函数, 调用这个函数,
可以同时生成一个图片和对应内容的文字信息. 使用方法如下所示:
# text 文本验证码
# image 验证码图片二进制流
text, image = captcha.generate_captcha()
四、(举例)业务逻辑分析
获取图形验证码:
- (1)、提取参数
- 前端传递的
uuid
—— 使用该uuid
作为key在redis中存储生成的验证码。
- 前端传递的
- (2)、校验参数
- 校验uuid的格式。
- (3)、业务数据处理
- 生成验证码图片
- 把图片验证码写入redis存储
- (4)、构建响应
- 响应中携带图片数据
4.1、前置任务:使用captcha
拓展包来生成验证码图片
注意,
captcha
包的使用需要提前安装依赖模块Pillow
,如下安装:
pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
编写一个demo,研究研究captcha
包的使用。
4.2、Django工程继承captcha
在文件夹
apps/verifications/
中新建包文件夹libs
。从上面的链接中找到
captcha
, 整体复制到libs
包中。
安装Pillow的图片库
添加captcha完成后,如果直接使用会报错:
报错原因:captcha 框架, 需要依赖 Pillow 这个包
在虚拟环境–安装 Python 处理图片的库 Pillow:
# 注意: 需要安装到虚拟环境中:
pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
4.3、获取图形验证码接口实现
新建verifications
应用。
4.3.1、定义视图
编辑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')
4.3.2、映射路由
编辑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()),
]
标签:uuid,python,redis,验证码,django,captcha,Pillow 来源: https://blog.csdn.net/weixin_56721790/article/details/117092665