首頁>技術>

環境說明:

系統:Windows10開發工具:PycharmPython版本:3.51. 建立Django基礎工程

直接使用Pycharm建立,當然你也可能使用命令列方式來建立Django工程,如圖正常在瀏覽器裡面能執行起來說明工程建立成功

建立工程

執行測試

執行正常

2. 給虛擬環境安裝django自帶驗證碼外掛包安裝方法如下# pip install django-simple-captcha (0.5.12)不過在Windows下可以直接使用Pycharm來安裝3. 核心程式碼新增驗證碼App,檔案Demo/settings.pyINSTALLED_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',]新增路由,Demo\\\\urls.pyfrom django.conf.urls import url, includefrom django.contrib import adminfrom app.views import refresh_captcha, Checkurlpatterns = [    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()),]在app裡面新建service.py,新增下面核心程式碼from captcha.helpers import captcha_image_urlfrom captcha.models import CaptchaStorefrom django.utils import timezonedef 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, "驗證碼錯誤"新增檢視,app\\views.pyimport jsonfrom django.http import HttpResponse, JsonResponsefrom django.shortcuts import render# Create your views here.from django.views import Viewfrom app.service import captcha, check_captchadef 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)4. 測試效果使用postman獲取驗證碼檢視圖形驗證碼

驗證碼校驗,驗證碼提示:驗證碼成功、驗證碼錯誤、驗證碼過期5. 其他配置

[官網文件地址] https://django-simple-captcha.readthedocs.io/en/latest/

具體細節閱讀官網文件內容,模式有好幾種:普通驗證碼校驗、單詞模式、計算模式等

# 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'

  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 架構師修煉之微服務部署 - 容器與叢集編排