图片验证码

一.django缓存设置

1.安装django缓存模块

pip install django-redis==4.12.1

2.settings.py中配置缓存

# 缓存配置
CACHES = {
	 # django存缓默认位置,redis 0号库
	 # default: 连接名称
	 "default": {
	 "BACKEND": "django_redis.cache.RedisCache",
	 "LOCATION": "redis://127.0.0.1:6379/0",
	 "OPTIONS": {
	 "CLIENT_CLASS": "django_redis.client.DefaultClient",
	 }
	 },
	 # django session存 reidis 1 号库(现在基本不需要使⽤)
	 "session": {
	 "BACKEND": "django_redis.cache.RedisCache",
	 "LOCATION": "redis://127.0.0.1:6379/1",
	 "OPTIONS": {
	 "CLIENT_CLASS": "django_redis.client.DefaultClient",
	 }
	 },
	 # 图形验证码,存redis 2号库
	 "img_code": {
	 "BACKEND": "django_redis.cache.RedisCache",
	 "LOCATION": "redis://127.0.0.1:6379/2",
	 "OPTIONS": {
	 "CLIENT_CLASS": "django_redis.client.DefaultClient",
	 }
	 }
}
# 配置session使⽤redis存储
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
# 配置session存储的位置: 使⽤cache中的
SESSION_CACHE_ALIAS = "session"

二.新建应用verifications

  • 图形验证码
  • 短信验证码
  • 邮件验证
'''2.1 在apps⽂件夹下新建应⽤: verifications'''
python ../manage.py startapp verifications # 切换到apps⽂件夹下执⾏创建命令

'''2.2 在syl/settings.py中添加应⽤'''
INSTALLED_APPS = [
 	'verifications.apps.VerificationsConfig',
]

'''2.3 在syl/urls.py主路由中添加'''
path('verify/', include('verifications.urls'))

'''2.4 添加⼦路由: verifications/urls.py'''
from django.urls import path
from . import views
urlpatterns = [
 	# path('image_codes/', views.ImageCodeView.as_view())
]

三.图形验证码

1.使用第三方包captcha

1.下载captcha压缩包captcha.zip,放到项⽬packages⽂件夹下
2.解压captcha.zip放到syl/libs⽂件夹下
3.解压⽂件中的syl/libs/captcha/captcha.py 右键运⾏即可⽣成图⽚验证码unzip xxx.zip

2.在verifications/views.py中使⽤
在这里插入图片描述
views中使用

import random

from django.http import HttpResponseForbidden, HttpResponse
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.views import APIView,Response

from libs.captcha.captcha import captcha
# Create your views here.
from django.views import View

# from utils.MyBaseView import send_sms
# from verificationsapp.tasks import send_sms

class ImageCodeView(View):
    def get(self, request):
        # 1.接收数据uuid
        uuid = request.GET.get('uuid')
        # 2.校验数据
        if not uuid:
            return HttpResponseForbidden('uuid无效')
        # 3.处理业务
        # 获取图片文本内容和图片二进制代码
        text, image = captcha.generate_captcha()  # text=GPMZ image=图片
        # 4.把uuid和图片文本存入redis
        redis_client = get_redis_connection('img_code')  # 获取redis客户端
        # 5.写入redis(是字符串)
        redis_client.setex(uuid, 60 * 5, text)
        # 6.返回响应图片
        return HttpResponse(image, content_type='image/jpg')


class SendSMCode(APIView):
    # 发送获取短信验证码
    def post(self, request):
        phone = request.data.get('phone')
        image_code = request.data.get('image_code')
        image_code_uuid = request.data.get('image_code_uuid')
        if not all([phone, image_code, image_code_uuid]):
            return Response({'code': 4005, 'msg': '参数不全'})

        redis_client = get_redis_connection('img_code')
        redis_img_code = redis_client.get(image_code_uuid).decode()
        if image_code.lower() != redis_img_code.lower():
            return Response({'code':4003,'msg':'参数错误'})

        #发送短信
        num = random.randint(100000,999999)
        send_data = {'code':num}
        # send_sms.delay(phone,send_data)
        print(send_data)
        #删除redis里的image_code 保存phone_code
        redis_client.setex(phone,60*60,num)
        redis_client.delete(image_code_uuid)
        # # #pipeline管道:作用就是把多个命令放在一起来执行
        # pl = redis_client.pipeline()
        # pl.setex(phone, 60 * 5, num)
        # pl.delete(image_code_uuid)
        # pl.execute()
        return Response({'code':0,'msg':'发送成功'})


在urls中

from django.contrib import admin
from django.urls import path,include
from verificationsapp import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()

urlpatterns = [
    path('image_codes/', views.ImageCodeView.as_view()),
    path('sms_codes/',views.SendSMCode.as_view())


]

3.测试接口

http://127.0.0.1:8000/verify/image_codes/?uuid=9b4381ed-06da-4ff6-ab56-56fbcbec5ef2
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值