Django_图形验证码


在这里插入图片描述
在网站开发的登录页面中,经常会需要使用到图形验证码来验证。在Django中,django-simple-captcha库包提供了图形验证码的使用。

Django-captcha是一个图形验证码第三方插件,官网地址:https://django-simple-captcha.readthedocs.io/en/latest/usage.html.。其用法主要有以下3步:

1.安装django-simple-captcha库

pip install django-simple-captcha

# 如果安装有依赖库问题,请执行下面的安装
apt-get -y install libz-dev libjpeg-dev libfreetype6-dev python-dev

2.设置

在settings中安装captcha应用

图1. 安装应用

设置captcha的基本样式

设置captcha的基本样式

captcha的输出样式由字符串:%(text_field)s %(image)s %(hidden_field)s,其中:

%(text_field)s表示用户输入验证码的输入框
%(image)s验证码图片
%(hidden_field)s隐藏域
captcha有三种基本验证码样式:

1.随机字符

CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge’​
在这里插入图片描述

2.简单数学计算

CAPTCHA_CHALLENGE_FUNCT = ‘captcha.helpers.math_challenge’
在这里插入图片描述

3.单词

CAPTCHA_CHALLENGE_FUNCT = ‘captcha.helpers.word_challenge’
在这里插入图片描述

在根路由中添加captcha的路由

图3. 设置路由
​最后要迁移数据库:

python manage.py migrate

之所以要迁移数据库是因为captcha不使用cookie和session保存验证码,而是由数据库保存,所以captcha需要迁移数据库生成表:
captcha的表结构
其中:

challenge存储是验证码字符串(表达式)、单词等,
response存储数学表达式的值,小写的验证码字符串;
hashkey是唯一标示
expiration过期时间

图5 字段说明

建立表单

比如说,一般情况下我们会在登录中使用图形验证码,使用captcha最简单的方法是用表单。

# forms.py
from django import forms
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
    username = forms.CharField(max_length=20,min_length=3)
    password = forms.CharField(max_length=128,widget=forms.PasswordInput())
    captcha = CaptchaField() # 验证码字段

用表单实现

应用路由设置:
urlpatterns = [
  	.....
    path('login/',views.user_login,name='login'),
]
视图函数:
import json

from django.contrib.auth import authenticate
import django.contrib.auth as auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

def user_login(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值