使用代码库captcha去生成随机验证码图片
1.首先在项目目录下创建验证码app
创建好一定记得要在settings文件中注册,并且格外注意别忘记末尾加逗号,否则直接报错
2.在应用app里面创建二级路由文件urls
from django.urls import path
from apps.verifycode.views import ImgCode
urlpatterns =[
path('image_codes/<uuid>/',ImgCode.as_view()),
]
3.在项目一级路由文件中加入二级路由
path('',include('apps.verifycode.urls'))
4.在验证码app中views文件中实现 ImgCode类用于请求时生成图片验证码
class ImgCode(View):
def get(self,request,uuid):
from libs.captcha.captcha import captcha
# text是验证码文本 img是验证码图片
text,img = captcha.generate_captcha()
# 用redis将图片验证码保存
from django_redis import get_redis_connection
redis_cli = get_redis_connection('code')
# name,time,value 名字,过期时间,值
redis_cli.setex(uuid,100,text)
# 返回图片验证码
# content_type 是响应体 需要告诉它是图片 image/jpeg
return HttpResponse(img,content_type='image/jpeg')
5.上一步引入captcha的操作还需要安装工具包的支持内库
pip install pillow
6.这样通过get请求携带uuid去访问就能获取到一张随机的二维码图片,其中二维码图片给前端页面,
uuid作为键,二维码的值作为值,被存储到redis数据库里。