Django-验证码

这篇讲什么

  • 验证码用在注册、登录这类容易被脚本轰炸的入口,作用是「先挡一道,不合格就不进后面的业务逻辑」;它能减少暴力请求,但不能替代 {% csrf_token %}。
  • 这篇先测 Pillow 这条路在 Django 5.2.19 上能不能走通,再指出老笔记那段手写验证码的三个真 bug 并给出修正版,最后对比现成的 django-simple-captcha。

作用

  • 在注册、登录页面为了防止暴力请求加入验证码:验证不通过就不进入后面的业务逻辑,省掉服务器和数据库的开销。
  • 它也能挡掉一部分自动化 CSRF 攻击(脚本拿不到图里的字符),但不能替代 {% csrf_token %},两者是不同层的防护。
  • 老笔记这套 Pillow 手写验证码在 Django 5.2 上仍然能跑,但有三个真 bug(下面实测),这一版把它们补上。

先测 Pillow 这条路能不能走通

  • 本机 Pillow 13.0.0,画图三件套都在:

    1
    from PIL import Image, ImageDraw, ImageFont
  • 字体是这段代码里最容易翻车的地方。实测:

    1
    2
    3
    4
    5
    6
    7
    truetype 签名 (font, size=10, index=0, encoding='', layout_engine=None) -> FreeTypeFont
    存在 True C:\Windows\Fonts\Arial.ttf
    存在 True C:\Windows\Fonts\consola.ttf
    存在 False /usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
    Linux 路径报错: OSError cannot open resource
    缺字体报错: OSError cannot open resource
    load_default -> FreeTypeFont
    • 也就是说老笔记里写死的 r'C:\Windows\Fonts\Arial.ttf' 只在 Windows 上成立,代码一上 Linux 服务器就是 OSError: cannot open resource(连不上任何友好提示)。
    • 正确做法是「候选列表 + 回退到 load_default()」,别写死一个路径。
  • Image.new / ImageDraw.Draw / draw.point / draw.text / im.save(buf, 'png') 都照旧可用,实测能出图:

    1
    2
    老笔记视图: 200 image/png 2425 字节  PNG头 True
    修正版: 200 image/png 2144 字节 字体 Arial.ttf Cache-Control: no-store, max-age=0

老笔记这段的三个真 bug

  • 1)session 里没有验证码时直接 .upper() 会炸

    老笔记的登录视图:

    1
    if verifycode.upper() == request.session.get("verifycode").upper():

    实测(新 session 直接提交):

    1
    无 session 时老写法: 500  AttributeError: 'NoneType' object has no attribute 'upper'
    • 用户先打开登录页、但验证码图没加载出来(或被广告拦截器挡了)就会撞上;正确写法是先取出来判 None。
  • 2)验证码不是一次性的

    • 老笔记只在生成时覆盖 request.session["verifycode"],验证通过后不删除。实测连续取两张图:

      1
      连续取两张图后的答案: hm2f -> Fdtt 长度 4
      • 只有最后一次有效,但验证成功后它仍留在 session 里,同一个码可以反复用来试账号密码。修正版在比对后 pop 掉,实测:

        1
        2
        第一次提交正确码: 302 /  session 剩余: None
        同一个码再用: 400(session 里已经没有可比对的值)
  • 3)用 str 当变量名

    1
    2
    str = '1234567890QWERTY...'
    rand_str += str[random.randrange(0, len(str))]
    • 这把内置的 str 类型遮蔽掉了,函数内后面任何 str(x) 都会 TypeError: 'str' object is not callable。改名成 CHARS 就好(PEP8 也要求模块级常量全大写)。
  • 另外两处不算 bug 但值得改:del draw(Pillow 对象自动回收,不需要手动 del)、img src="http://127.0.0.1:8000/verifycode/"(写死主机,换域名就失效,改成 {% url %})。

修正版:视图

myapp/views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import io
import os
import random

from django.http import HttpResponse
from django.shortcuts import redirect, render
from PIL import Image, ImageDraw, ImageFont

CHARS = "1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
FONT_CANDIDATES = [
r"C:\Windows\Fonts\Arial.ttf",
r"C:\Windows\Fonts\consola.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
]


def _font(size=32):
"""按候选列表找字体,全都找不到就退回 Pillow 自带默认字体。"""
for path in FONT_CANDIDATES:
if os.path.exists(path):
return ImageFont.truetype(path, size), path
return ImageFont.load_default(), "load_default"


def verifycode(request):
width, height = 120, 44
code = "".join(random.choice(CHARS) for _ in range(4))

im = Image.new("RGB", (width, height), (random.randrange(20, 100),) * 3)
draw = ImageDraw.Draw(im)
for _ in range(120): # 噪点
draw.point((random.randrange(width), random.randrange(height)),
fill=(random.randrange(255), 255, random.randrange(255)))

font, used = _font(32)
x = 6
for ch in code: # 按实际字宽排布,不再写死 5/25/50/75
box = draw.textbbox((0, 0), ch, font=font)
draw.text((x, 4), ch, font=font,
fill=(255, random.randrange(0, 255), random.randrange(0, 255)))
x += box[2] - box[0] + 6

buf = io.BytesIO()
im.save(buf, "png")

request.session["verifycode"] = code
resp = HttpResponse(buf.getvalue(), "image/png")
resp["Cache-Control"] = "no-store, max-age=0" # 关键:别让浏览器缓存这张图
resp["X-Captcha-Font"] = os.path.basename(used)
return resp


def login(request):
if request.method == "GET":
return render(request, "myapp/login.html")

typed = request.POST.get("verifycode") or ""
saved = request.session.get("verifycode")
if saved is None: # 先判空,不再 .upper() 炸在 None 上
return HttpResponse("验证码已失效,请刷新页面", status=400)
request.session.pop("verifycode") # 一次性

if typed.upper() != saved.upper():
return redirect("/login/?why=captcha")
if request.POST.get("username") == "sunck" and request.POST.get("passwd") == "ok":
request.session["uid"] = 1
return redirect("/")
return redirect("/login/?why=credentials")
  • 实测这几条路径(django.test.Client,会自动带 Cookie):

    1
    2
    3
    错码:         302 /login/?why=captcha
    用小写提交正确答案: 302 / uid in session: True
    凭证错: 302 /login/?why=credentials
    • 大小写不敏感是靠两边都 .upper() 实现的,老笔记这点没错。
  • Cache-Control: no-store 为什么重要:验证码是 <img>,浏览器会按 URL 缓存它。不加这个头时,用户点「刷新页面」拿到的还是同一张图,但 session 里的答案已经换新,于是怎么输都错。前端再配一个时间戳参数强制刷新:

    1
    2
    <img src="{% url 'myapp:verifycode' %}" alt="验证码"
    onclick="this.src='{% url 'myapp:verifycode' %}?t='+Date.now()">

    实测登录页渲染出的 img 就是这个形状,src 走 {% url %} 而不是写死 http://127.0.0.1:8000/...。

登录页模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>
<form action="{% url 'myapp:login' %}" method="POST">
{% csrf_token %}
账号:<input type="text" name="username"><br>
密码:<input type="password" name="passwd"><br>
验证码:<input type="text" name="verifycode">
<img src="{% url 'myapp:verifycode' %}" alt="验证码"
onclick="this.src='{% url 'myapp:verifycode' %}?t='+Date.now()">
<input type="submit" value="登陆">
</form>
</body>
</html>
  • 实测 GET /login/ → 200,页面里含 csrfmiddlewaretoken 隐藏域。
  • 老笔记的表单 action="/login/"、method="POST" 都没问题,只是少了「刷新验证码」的交互(点击 <img> 换图)。

用现成的库:django-simple-captcha

  • 本机装了 django-simple-captcha 0.7.0。它把答案存在数据库表里(CaptchaStore 模型),比塞 session 更适合多进程部署。

  • 但必须先把 'captcha' 加进 INSTALLED_APPS 再导入,否则实测直接报错:

    1
    2
    RuntimeError: Model class captcha.models.CaptchaStore doesn't declare an explicit
    app_label and isn't in an application in INSTALLED_APPS.
  • 最小接入(四步):

    settings.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    INSTALLED_APPS = [..., "captcha"]

    # urls.py
    path("captcha/", include("captcha.urls")),

    # forms.py
    from captcha.fields import CaptchaField

    class LoginForm(forms.Form):
    verify = CaptchaField()

    # 视图里正常 form.is_valid() 即可,答案校验由字段自己做
  • 想要更省事就用它,别自己画图:字体、干扰线、过期清理(captcha.management.commands.cleancaptcha)都替你处理好了。

新手卡点清单

  • 都是实测过的:

    卡点 症状 正确做法
    字体路径写死 Windows 上 Linux 就 OSError: cannot open resource 候选列表 + load_default() 兜底
    request.session.get("verifycode").upper() AttributeError: 'NoneType' object has no attribute 'upper'(500) 先判 None
    验证通过不删 session 里的码 同一个码可反复试密码 比对后 pop 掉,一次性
    验证码响应没禁缓存 刷新后图不变、怎么输都错 Cache-Control: no-store + ?t= 时间戳
    用 str 当变量名 后续 str(...) 变 TypeError 改名 CHARS
    img src 写死 127.0.0.1:8000 换域名/端口图就挂 用 {% url %}
    未装 sessions 应用 request.session 不存在/不落库 确认 django.contrib.sessions 在 INSTALLED_APPS 且跑过 migrate
    直接 from captcha.fields import ... RuntimeError ... isn't in an application in INSTALLED_APPS 先 'captcha' 进 INSTALLED_APPS

参考

本文结束 感谢您的阅读
正在加载今日诗词....