django-sample-captcha文档地址:https://django-simple-captcha.readthedocs.io/en/latest/usage.html
在实际生活中,常会遇到验证码,验证码技术阻挡了不少的恶意的爬取,当然,反爬技术也是与时俱进.django在实现验证码的上,有一个第三方的库,安装方式如下:
pip install django-simple-captcha
功能可以说很强大,可以满足日常的需要,内置多种验证的形式,如加减法,英文,数字等。
一般用法:
先在设置中注册应用
再在URL中配置
url(r'^captcha/', include('captcha.urls')),
在相应的forms.py文件中,
from captcha.fields import CaptchaField
captcha = CaptchaField(error_messages={"invalid": "验证码错误"},)
接着在模板中使用
{{形式}}或者具体的{{login_form.captcha}},刷新页面就会有一个验证码,但是每次使用都需要刷新,非常不方便,体验性也差。
有什么办法解决。
使用AJAX刷新
先分析页面中的验证码。
验证码只是改变了IMG SRC中的地址和ID = “id_reg_captcha_0” 中值的值,改变这两个值就可以改变验证码。
但使用上面的普通方式很难使用改变,并且验证码的样式也不好定制。那么可以考虑自定义表单,只需要在后端产生图片和键就可以很方便定制。
url.py:
from students.views import refresh_captcha
url(r'refresh/$', refresh_captcha, name='captcha-refresh')
views.py
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
def get(self, request):
login_form = LoginForm()
hashkey = CaptchaStore.generate_key() # 验证码的key
# 图片地址
imgage_url = captcha_image_url(hashkey)
return render(request, 'index.html', {"login_form": login_form, "hashkey": hashkey, "imgage_url": imgage_url})
def refresh_captcha(request):
to_json_response = dict()
to_json_response['status'] = 1 # ajax的状态
to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
return HttpResponse(json.dumps(to_json_response), content_type='application/json')
在文档中,这一块代码比较多,但核心代码就只需要钥匙和地址。
AJAX代码:
$('.next-captcha').click(function () {
$.getJSON("{% url 'captcha-refresh' %}", function (result) {
$('.captcha').attr('src', result['new_cptch_image']);
$('#id_reg_captcha_0').val(result['new_cptch_key'])
});
});