第38章 Django集成验证码

在实现验证码功能的第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 HttpResponse
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
import 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 path
from . import views
urlpatterns = [
path('captcha/', views.captcha),
path('check_captcha/', views.check_captcha),
]

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

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

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

发布了21 篇原创文章 · 获赞 2 · 访问量 3081

猜你喜欢

转载自blog.csdn.net/a_faint_hope/article/details/103782477
今日推荐