Python——Django框架——django-simple-captcha(验证码)
生活随笔
收集整理的這篇文章主要介紹了
Python——Django框架——django-simple-captcha(验证码)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、引用 包
pip install django-simple-captcha
二、將captcha加入setting的 INSTALLED_APPS
三、運行python manager.py migrations 和 python manage.py migrate
四、加入路徑
path('captcha/',include('captcha.urls))
五、引入Form表單
from captcha.fields import CaptchaFieldclass captcha = CaptcchaField()#生成圖片驗證碼和輸入框六、ajax動態驗證
from django.http import JsonResponse from captcha.models import CaptchaStoredef ajax_val(request):if request.is_ajax():cs = CaptchaStore.objects.filter(response=request.GET['response'], hashkey=request.GET['hashkey'])if cs:json_data={'status':1}else:json_data = {'status':0}return JsonResponse(json_data)else:# raise Http404json_data = {'status':0}return JsonResponse(json_data) view.py path(r'^ajax_val/',views.ajax_val, name='ajax_val'), #動態驗證的路由 <script>$(function(){$('#id_captcha_1').blur(function(){// #id_captcha_1為輸入框的id,當該輸入框失去焦點是觸發函數 json_data={'response':$('#id_captcha_1').val(), // 獲取輸入框和隱藏字段id_captcha_0的數值'hashkey':$('#id_captcha_0').val()}$.getJSON('/ajax_val', json_data, function(data){//ajax發送 $('#captcha_status').remove()if(data['status']){ //status返回1為驗證碼正確, status返回0為驗證碼錯誤, 在輸入框的后面寫入提示信息 $('#id_captcha_1').after('<span id="captcha_status" >*驗證碼正確</span>')}else{$('#id_captcha_1').after('<span id="captcha_status" >*驗證碼錯誤</span>')}});});})</script><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> tempalte七、ajax刷新
path(r’refresh/$’, views.captcha_refresh, name=’captcha-refresh’) # 只是源碼介紹不用寫入自己的代碼中 def captcha_refresh(request):""" Return json with new captcha for ajax refresh request """if not request.is_ajax():# 只接受ajax提交raise Http404new_key = CaptchaStore.generate_key()to_json_response = {'key': new_key,'image_url': captcha_image_url(new_key),}return HttpResponse(json.dumps(to_json_response), content_type='application/json') view.py $(function(){$('.captcha').css({'cursor': 'pointer'})# ajax 刷新$('.captcha').click(function(){console.log('click');$.getJSON("/captcha/refresh/",function(result){$('.captcha').attr('src', result['image_url']);$('#id_captcha_0').val(result['key'])});}); ajax刷新?
?
?
| |
轉載于:https://www.cnblogs.com/cxys85/p/10867358.html
總結
以上是生活随笔為你收集整理的Python——Django框架——django-simple-captcha(验证码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简述软件黑盒测试的方法,简述什么是黑盒测
- 下一篇: oracle财务软件凭证打印,金算盘财务