分享

第38章 Django集成验证码

 正合叔 2021-01-10

在实现验证码功能的第3方库当中,要数captcha最为成熟,用的人也最多,咱也不例外,用pip3进行下载和安装。

38.1 captcha注册

在settings.py中的INSTALLED_APPS节点注册captcha。如果要调整与验证码相关的配置,也在这里进行。背景色、前景色、字体大小等都可以进行调整,更多内容,可到官网上查看。

INSTALLED_APPS = [ 'simpleui', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'captcha',]# 样式CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null', 'captcha.helpers.noise_arcs', # 线 #'captcha.helpers.noise_dots', # 点)# 字体角度CAPTCHA_LETTER_ROTATION = (-10, 10)# 背景色CAPTCHA_BACKGROUND_COLOR = '#f5f7fa'# captcha 图片大小CAPTCHA_IMAGE_SIZE = (72, 28)# 验证码随机数个数CAPTCHA_LENGTH = 4

执行数据迁移命令,生成captcha所依赖的表。

python3 manage.py migrate

38.2 创建和验证

新建一个应用special, 新建urls.py文件,编写views.py文件。这个应用没有数据表要生成,可以不用集成到settings.py中。

from django.http import HttpResponsefrom captcha.models import CaptchaStorefrom captcha.helpers import captcha_image_urlimport json# 创建验证码def captcha(request): hash_key = CaptchaStore.generate_key() image_url = captcha_image_url(hash_key) captcha_str = {'hashkey': hash_key, 'image_url': image_url}return HttpResponse(json.dumps(captcha_str), content_type='application/json')# 验证验证码def check_captcha(request): hash_key = request.GET.get('hash_key', '') captcha_str = request.GET.get('captcha_str', '') if captcha_str and hash_key: # 取根据hashkey获取数据库中的response值 get_captcha = CaptchaStore.objects.get(hashkey=hash_key) # 如果验证码匹配 if get_captcha.response == captcha_str.lower(): result = True else: result = False else: result = False return HttpResponse(json.dumps({'result':result}), content_type='application/json')

打开special/urls.py文件,配置内容如下。

from django.urls import pathfrom . import viewsurlpatterns = [    path('captcha/', views.captcha),    path('check_captcha/', views.check_captcha),]

百万、千万别忘记把special/urls.py集成到sales/urls.py中。说太多不如代码来的直观,粘贴出来了,请欣赏。

from django.contrib import adminfrom django.urls import path, includeadmin.site.site_title = '销售管理系统'admin.site.site_header = '销售管理系统'urlpatterns = [ path('', admin.site.urls), path('captcha/', include('captcha.urls')), path('special/', include('special.urls')),]

就这样悄无声息,简单明了地集成好了。有关验证码地局部调用和刷新,请见下一篇。

第38章 Django集成验证码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多