您的位置:首页 > 科技 > IT业 > 制作人韩剧_怎么选择模板建站服务_网站流量排名_南京seo排名扣费

制作人韩剧_怎么选择模板建站服务_网站流量排名_南京seo排名扣费

2024/10/7 0:14:53 来源:https://blog.csdn.net/2301_77160836/article/details/142420708  浏览:    关键词:制作人韩剧_怎么选择模板建站服务_网站流量排名_南京seo排名扣费
制作人韩剧_怎么选择模板建站服务_网站流量排名_南京seo排名扣费

前言:

   对于具有评论功能的博客来说,无论是否为知名博客,都会被恶意广告关注,上线没几天就会有人开始通过程序灌入广告评论,因此针对所有有用户输入的页面,验证码是必需品。

   在Django系统中使用验证码非常简单,因为有足够多的库供你选择,只要到djangositepackages网站搜索下就能看到:https://djangopackages.org/grids/g/captcha/

一、使用 django-simple-captcha

   要实现一个验证码,最简单的方式就是找一个使用量最大的库,或者GitHub上star数最多、最活跃的项目。只需要根据它的使用说明配置即可,比如我们将要用到的django-simple-captcha。

   第一步安装:

pip install django-simple-captchao

   第二步是配置 INSTALLED_APPS,修改settings.py:

INSTALLED_APPS = ['typeidea','blog.apps.BlogConfig','config.apps.ConfigConfig','comment.apps.CommentConfig','captcha',#省略其他配置
]

   第三步是配置urls.py:

# typeidea/urls.py
from django.urls import path, re_path, includeurlpatterns = [#省略其他配置path('captcha/', include('captcha.urls')),
]

   第四步是配置comment/forms.py:

# comment/forms.py
from captcha.fields import CaptchaFieldclass CommentForm(forms.ModelForm):# 省略其他代码captcha = CaptchaField()

   第五步是创建表:

 python manage.py migrate

   最后得到的验证码示例页面如下图所示:

在这里插入图片描述

二、配置验证码的几个要素

   如果仅仅是使用的话,那么只需要经过上面5个步骤就好了,方便、简单、快捷。但是如果老板要求你来根据自己的业务实现验证码的话,那么怎么做呢?如果你没有梳理清楚验证码的实现逻辑,基本上不可能自己来实现一套验证机制。

   我们梳理一下django-simple-captcha的实现逻辑,有这么几个要素:

  • 用户端验证码的唯一标识;
  • 在图片URL中通过唯一标识获取到对应的图片;
  • 后端存储已经生成过的验证码及标识;
  • 通过用户端的标识以及用户输入的验证码来判断是否存在这条记录。

   在整个过程中,你会觉得跟用户名和密码验证很相似,只是密码是实时生成到图片中的。

三、配置Ajax校验验证码

   理解了原理之后,要修改为Ajax验证的方式就很容易了。我们只需要实现通过接口拿到验证码标识以及验证码,然后判断数据库中是否存在即可。下面我们直接基于这个插件来改造。

   现在开发接口。在comment/views.py中增加如下代码:

from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.http import JsonResponse
from django.utils import timezoneclass VerifyCaptcha(View):def get(self, request):captcha_id = CaptchaStore.generate_key()return JsonResponse({'captcha_id': captcha_id,'image_src': captcha_image_url(captcha_id),})def post(self, request):captcha_id = request.POST.get('captcha_id')captcha = request.POST.get('captcha', '')captcha = captcha.lower()try:CaptchaStore.objects.get(response=captcha, hashkey=captcha_id, expiration__gt=timezone.now()).delete()except CaptchaStore.DoesNotExist:return JsonResponse({'msg': '验证码错误'}, status=400)return JsonResponse({})

   在View里面我们完成了两件事:在get中生成图片验证码,在post中校验验证码以及清理掉校验通过的验证码。

   接下来,配置templates/comment/block.html,修改form位置的定义,并在下面新增script代码:

<hr/>
<div class="comment"><form id="comment_form" class="form-group" action="/comment/" method="POST">{% csrf_token %}<input name="target" type="hidden" value="{{ target }}"/>{{ comment_form }}<div id="captcha_section"></div><input id="verify" type="button" value="写好了!"/><input id="submit" type="submit" style="display:None" value="写好了!"/></form><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script><script>$(document).ready(function(){var $form = $('.form-group');function init_captcha(){$.getJSON("{% url 'verify_captcha' %}", function(data){$('#captcha_section').html('<img src="' + data.image_src + '" id="captcha_id" data-id="'+ data.captcha_id +'"/>' +'<input id="captcha"/>');})}$( document ).on("click", '#captcha_id', init_captcha);$('#verify').on('click', function(){var captcha = $('#captcha').val();if (!captcha){alert('验证码不能为空');return;}$.ajax({url: "{% url 'verify_captcha' %}",method: 'POST',data: {'captcha_id': $('#captcha_id').data('id'),'captcha': captcha,'csrfmiddlewaretoken': '{{ csrf_token }}',},success: function(){$('#submit').click();setTimeout(init_captcha, 500);},error: function(res, data){alert(res.responseJSON.msg);return false;}});});init_captcha();});</script><!-- 评论列表 --><ul class="list-group">{% for comment in comment_list %}<li class="list-group-item"><div class="nickname"><a href="{{ comment.website }}">{{ comment.nickname }}</a> <span>{{ comment.created_time }}</span></div><div class="comment-content">{% autoescape off %}{{ comment.content }}{% endautoescape %}</div></li>{% endfor %}</ul>
</div>

   修改urls.py配置:

# typeidea/urls.py
from comment.views import CommentView, VerifyCaptchaurlpatterns = [# 省略其他配置path('captcha/', include('captcha.urls')),path('verify_captcha/', VerifyCaptcha.as_view(), name='verify_captcha'),
]

   在上面的代码中,comment/forms.py中关于验证码部分的配置可以去掉了。

总结

   当我们使用一个新组件时,需要尽可能理解它的运行原理,这样我们在必要时可以很方便地对其进行定制,甚至根据这套原理来自行实现。

参考资料

django-simple-captcha文档:
http://django-simple-captcha.readthedocs.io/en/latest/

链接:

项目开源代码GitHub:https://github.com/1273055646/typeidea/tree/A-simple-captcha

Django学习实战篇一(适合略有基础的新手小白学习)(从0开发项目)

Django学习实战篇二(适合略有基础的新手小白学习)(从0开发项目)

Django学习实战篇三(适合略有基础的新手小白学习)(从0开发项目)

Django学习实战篇四(适合略有基础的新手小白学习)(从0开发项目)

Django学习实战篇五(适合略有基础的新手小白学习)(从0开发项目)

Django学习实战篇六(适合略有基础的新手小白学习)(从0开发项目)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com