環境說明:
- 系統:Windows10
- 開發工具:Pycharm
- Python版本:3.5
1. 創建Django基礎工程
直接使用Pycharm創建,當然你也可能使用命令行方式來創建Django工程,如圖正常在瀏覽器裡面能運行起來說明工程創建成功
2. 給虛擬環境安裝django自帶驗證碼插件包
- 安裝方法如下
<code># pip install django-simple-captcha (0.5.12)/<code>
- 不過在Windows下可以直接使用Pycharm來安裝
3. 核心代碼
- 添加驗證碼App,文件Demo/settings.py
<code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app.apps.AppConfig', 'captcha' ] # 需要屏蔽csrf,會影響post請求 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]/<code>
- 添加路由,Demo\urls.py
<code>from django.conf.urls import url, include from django.contrib import admin from app.views import refresh_captcha, Check urlpatterns = [ url(r'^admin/', admin.site.urls), # Django驗證碼插件註冊,不能刪除 url(r'^captcha', include('captcha.urls')), # 獲取驗證碼或者刷新驗證碼接口 url(r'^refresh_captcha$', refresh_captcha), # 校驗驗證碼是否正確 url(r'^check_captcha$', Check.as_view()), ]/<code>
- 在app裡面新建service.py,添加下面核心代碼
<code>from captcha.helpers import captcha_image_url from captcha.models import CaptchaStore from django.utils import timezone def captcha(): """ 創建驗證碼 :return: """ hash_key = CaptchaStore.generate_key() # 驗證碼答案 image_url = captcha_image_url(hash_key) # 驗證碼地址 return {'hash_key': hash_key, 'image_url': image_url} def check_captcha(captcha_str, captcha_hash_key): """ 驗證驗證碼 :param captcha_str: :param captcha_hash_key: :return: """ if captcha_str and captcha_hash_key: try: # 獲取根據hashkey獲取數據庫中的response值 get_captcha = CaptchaStore.objects.get(hashkey=captcha_hash_key) if get_captcha.response == captcha_str.lower(): # 如果驗證碼匹配 if get_captcha.expiration > timezone.now(): return True, "驗證成功" else: return False, "驗證碼過期" except: return False, "驗證碼錯誤" return False, "驗證碼錯誤" /<code>
- 添加視圖,app\views.py
<code>import json from django.http import HttpResponse, JsonResponse from django.shortcuts import render # Create your views here. from django.views import View from app.service import captcha, check_captcha def refresh_captcha(request): """ 刷新驗證碼、獲取驗證碼 :param request: :return: """ results = {'status': 0, 'msg': '獲取成功', 'data': captcha()} return HttpResponse(json.dumps(results), content_type='application/json') class Check(View): """驗證碼校驗""" def post(self, request): results = {'status': 1, 'msg': '校驗失敗'} try: data = json.loads(request.body.decode()) captcha = data['captcha'] hash_key = data['hash_key'] status, msg = check_captcha(captcha, hash_key) results = {'status': 0 if status else 1, 'msg': msg} except Exception as error: print(error) return JsonResponse(results) /<code>
4. 測試效果
- 使用postman獲取驗證碼
- 查看圖形驗證碼
- 驗證碼校驗,驗證碼提示:驗證碼成功、驗證碼錯誤、驗證碼過期
5. 其他配置
[官網文檔地址] https://django-simple-captcha.readthedocs.io/en/latest/
具體細節閱讀官網文檔內容,模式有好幾種:普通驗證碼校驗、單詞模式、計算模式等
<code> # Django圖形驗證碼配置 # 字母驗證碼 # 設置 captcha 圖片大小 CAPTCHA_IMAGE_SIZE = (150, 45) # 字體大小 CAPTCHA_FONT_SIZE = 36 # 字符個數 CAPTCHA_LENGTH = 4 # 超時(minutes) CAPTCHA_TIMEOUT = 10 # 驗證碼的背景顏色 CAPTCHA_BACKGROUND_COLOR = '#ffffff' # 字體路徑 CAPTCHA_FONT_PATH = './conf/Phosphate-Inline.ttf' # 加減乘除驗證碼 # 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.math_challenge'/<code>