回到顶部

CONTENTS

django-simple-captcha 图形验证码

官方文档

https://django-simple-captcha.readthedocs.io/en/latest/usage.html

https://github.com/mbi/django-simple-captcha

个人用法

未使用到 Django 的表单的验证

view 里调用生成验证码的代码

from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url

from ipware.ip import get_ip

def view_test(request):
	# hashkey 验证码生成的秘钥,image_url 验证码的图片地址
	hashkey_name = "hashkey_%s" % get_ip(request)
	hashkey = cache.get(hashkey_name)
	if not hashkey:
	    hashkey= CaptchaStore.generate_key()
	    cache.set(hashkey_name, hashkey, 60 * 1)
	image_url = captcha_image_url(hashkey)

	return ""  # 此处省略

前端代码

<div class="m-form-group am-u-sm-6 blog-clear-right">
    <div class="am-input-group">
        <input autocomplete="off" id="id_captcha_1" name="captcha_code" type="text"
               placeholder="* 验证码" class="am-form-field" required="required">
        <span class="am-input-group-btn">
            <img src="{{ image_url }}" alt="captcha" class="captcha" id="captcha"
                 style="height: 38px;">
        </span>

        <input id="id_reg_captcha_0" name="captcha_hashkey" type="hidden" value="{{ hashkey }}">
    </div>
    <script>
        $('#captcha').click(function () {
            $.getJSON("/captcha/refresh/", function (result) {
                if (result['code'] === 200) {
                    $('#captcha').attr('src', result['image_url']);
                    $('#id_reg_captcha_0').val(result['key'])
                } else {
                    toastr.warning(result['msg']);
                }
            });

        });
    </script>
</div>

view 里验证验证码是否有效

from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url

from ipware.ip import get_ip

def view_test_2(request):
	ip = get_ip(request)

	# 前端回传:captcha_code 验证码的值,captcha_hashkey 哈希之后的值
    try:
        # 如果没过期找到了就删除掉
        CaptchaStore.objects.get(response=captcha_code.lower(), hashkey=captcha_hashkey,
                                 expiration__gt=timezone.now()).delete()
        if cache.has_key("hashkey_%s" % ip):
            # 验证通过,如果还存在 key, 就删除掉
            cache.delete("hashkey_%s" % ip)

    except CaptchaStore.DoesNotExist:
        return HttpResponse("验证码无效或已过期")

	return ""  # 此处省略

其他用法

https://my.oschina.net/hellotest/blog/1623597

^_^
请喝咖啡 ×

前一篇: jQuery 实现富文本的标题自动生成目录
下一篇: Django MemCache 缓存使用方法和源码
captcha
带 * 是必填项