栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

django 实现图片验证码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django 实现图片验证码

1.下载

pip install django-simple-captcha

2.在settings文件中配置

INSTALLED_APPS = [
    'captcha'
]

3.设置图片的风格

# 字母验证码
CAPTCHA_IMAGE_SIZE = (80, 45)  # 设置 captcha 图片大小
CAPTCHA_LENGTH = 4  # 字符个数
CAPTCHA_TIMEOUT = 1  # 超时(minutes)

# 加减乘除验证码
CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null',
                           'captcha.helpers.noise_arcs',  # 线
                           'captcha.helpers.noise_dots',  # 点
                           )
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'

4.执行

python manage.py makemigrations
python manage.py migrate

5.配置路由

from django.contrib import admin
from django.urls import path,include,re_path
from bffile_data.views import Captcha

urlpatterns = [
    path('bfresource_platform/', include("captcha.urls")),
    re_path('captcha/', Captcha.as_view(),name="captcha"),
]

6.在工具包中编写

from captcha.models import CaptchaStore
from captcha.helpers import  captcha_image_url

def create_captcha():
    hashkey = CaptchaStore.generate_key()
    image_url = captcha_image_url(hashkey)
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha

def jarge_captcha(captchaStr, captchaHashkey):
    if captchaStr and captchaHashkey:
        try:
            get_captcha = CaptchaStore.objects.get(hashkey=captchaHashkey)
            if get_captcha.response == captchaStr.lower():
                return True
        except:
            return False
    else:
        return False

7.在视图函数中编写

from rest_framework.generics import GenericAPIView
from rest_framework import mixins, status
class Captcha(GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin):

    def get(self, request):
        captcha = ts.create_captcha()
        result = ts.result_data(status.HTTP_200_OK, captcha, "成功")
        return Response(result)

    def post(self, request):
        data_body = request.data
        user_id = data_body.get("user_id")
        user_name = data_body.get("user_name")
        if not models.Person_info.objects.get(person_id=user_id, person_name=user_name):
            result = ts.result_data(status.HTTP_402_PAYMENT_REQUIRED, None, "账户名不正确")
            return Response(result)
        capt = data_body.get("captcha")
        key = data_body.get("hashkey")
        if not ts.jarge_captcha(capt, key):
            result = ts.result_data(status.HTTP_200_OK, None, "验证码不正确")
            return Response(result)
        result = ts.result_data(status.HTTP_200_OK, None, "验证码正确")
        return Response(result)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号