21-图形验证码

发布时间 2023-03-28 18:40:39作者: 测试圈的彭于晏

配置

# 0. 官网
    https://django-simple-captcha.readthedocs.io/en/latest/advanced.html

# 1. 安装 django-simple-captcha库
    pip install django-simple-captcha

# 2. 在settings.py中注册应用
    INSTALLED_APPS = [captcha,]

# 3. 在settings.py中添加图形验证码设置
'''
    # 图形验证码设置
    CAPTCHA_IMAGE_SIZE = (80, 45)  # 设置captcha 图片大小
    CAPTCHA_LENGTH = 4  # 字符个数
    CAPTCHA_TIMEOUT = 1  # 超时(minutes)

    # 输出格式:输入框 验证码图片 隐藏域
    CAPTCHA_OUTPUT_FORMAT = '%(text_field)s %(image)s %(hidden_field)s'
    CAPTCHA_NOISE_FUNCTIONS = (
        'captcha.helpers.noise_null',
        'captcha.helpers.noise_arcs', # 线
        'captcha.helpers.noise_dots', # 点
    )

    # 随机字符验证码
    CAPTCHA_CHALLENGE_FUNCT ='captcha.helpers.random_char_challenge'
'''

# 4. 主应用 urls.py 中添加 captcha 路径
  urlpatterns = [
    path('captcha/', include("captcha.urls")), # 图片验证码路由
    ]

# 5. 配置完,进行数据库迁移 ,生成 captcha_captchastore 表
    python manage.py migrate
# 6. 建立表单 forms.py
    from django.forms import forms
    from captcha.fields import CaptchaField
    class LoginForm(forms.Form):
        captcha = CaptchaField() # 验证码字段

实现

# 1. 创建urls,py
    from App03 import views
    app_name="App03"
    urlpatterns = [
        path('refresh_captcha/', views.refresh_captcha) # 刷新验证码
        path('cap/',views.handle_captcha,name="cap"), # 验证验证码
      
    ]

# 2. 创建html
<body>
<form action="{% url 'App03:cap' %}" method="post">
    {% csrf_token %}
    {{ form.captcha }} {{ form.captcha.errors }}<br>
    <input type="submit">
</form>
</body>
</html>
# 点击刷新验证码
<script src="https://cdn.bootcss.com/jquery/1.12.3/jquery.min.js"></script>
<script>
       //点击刷新验证码
    $(function () {
        $('.captcha').css({
            'cursor': 'pointer'
        });
        //ajax刷新
        $('.captcha').click(function () {
            console.log('click');
             // $.get("{% url 'captcha-refresh' %}")  直接访问这个自带路径也能涮新验证码
            $.getJSON('/refresh_captcha/', function (result) {
                alert(result["image_url"]);
                $('.captcha').attr('src', result["image_url"]);
                $('#id_captcha_0').val(result["key"]);
            });
        });
    })
</script>
# 3. 编写视图函数
# 刷新验证码
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore

def refresh_captcha(request):
    data = {"key": CaptchaStore.generate_key(),
            "image_url": captcha_image_url(CaptchaStore.generate_key())}
    return HttpResponse(json.dumps(data))


# 验证验证码
def handle_captcha(request):
    if request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            print("验证通过")
            return HttpResponse("验证通过")
        else:
            return render(request, 'app03/verifycode.html', locals())
    else:
        form = LoginForm()
        # # print(form)
        # img = re.findall(r'<img src="(/.+/)"', str(form))[0]
        # val = re.findall(r'value="(.+)"', str(form))[0]
        return render(request, 'app03/verifycode.html', locals())



前后端分离

# urls.py
  path('yzm/', views.output_yzm, name="yzm")
# view.py
# 不使用表单
def output_yzm(request):
    new_key = CaptchaStore.pick()
    image_url = captcha_image_url(new_key)
    return render(request, 'vc.html', locals())
# vc.html
<body>
<form action="" method="post">
    <input type="text" name="yzm"> <img src="{{ image_url }}" alt="" class="captcha"> <br>
    <input  id="id_captcha_0" type="hidden" name="code" value="{{ new_key }}">
    <input type="submit">
</form>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/1.12.3/jquery.min.js"></script>
<script>
    //点击刷新验证码
    $(function () {
        $('.captcha').css({
            'cursor': 'pointer'
        });
        //ajax刷新
        $('.captcha').click(function () {
            console.log('click');
            $.get("{% url 'captcha-refresh' %}",
                function (result) {
                $('.captcha').attr('src', result["image_url"]);
                $('#id_captcha_0').val(result["key"]);
            });
        });
    })
</script>