相关模块

django-simple-captcha

  1. pip install django-simple-captcha

配置URL

先将captcha添加到url中

  1. urlpatterns = [
  2. path('captcha/', include('captcha.urls')),
  3. ]

该模块是如何生成图形验证码的

在生成图形验证码时,会先生成图形验证码上显示的字符challenge、正确的答案response、用来唯一表示图形验证码的hashkey、以及过期时间expiration,然后将这些数据存入数据库

  1. class CaptchaStore(models.Model):
  2. id = models.AutoField(primary_key=True)
  3. challenge = models.CharField(blank=False, max_length=32)
  4. response = models.CharField(blank=False, max_length=32)
  5. hashkey = models.CharField(blank=False, max_length=40, unique=True)
  6. expiration = models.DateTimeField(blank=False)

然后根据challenge的值生成图片,返回给客户端

常用方法

  1. from captcha.models import CaptchaStore

生成图形验证码

  1. CaptchaStore.generate_key()
  1. CaptchaStore.pick()

移除数据库中存储的过期的验证码

  1. CaptchaStore.remove_expired()

验证图形验证码

  1. def check_captcha(captcha_hashkey, captcha_response):
  2. CaptchaStore.remove_expired()
  3. try:
  4. store = CaptchaStore.objects.get(hashkey=key)
  5. except CaptchaStore.DoesNotExist:
  6. # HTTP 410 Gone status so that crawlers don't index these expired urls.
  7. return HttpResponse(status=410)
  8. return captcha_response == store.response

获取图形验证码URL

  1. from captcha.helpers import captcha_image_url
  2. captcha_url = captcha_image_url(hashkey)

全局配置项

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

配置项 描述 默认值
CAPTCHA_GET_FROM_POOL_TIMEOUT 验证码的过期时间 5(分钟)
CAPTCHA_CHALLENGE_FUNCT 用来生成验证码的函数 captcha.helpers.random_char_challenge






CaptchaStore.generate_key

generator用来表示生成图形验证码的函数,默认是配置项CAPTCHA_CHALLENGE_FUNCT指定的函数(captcha.helpers.random_char_challenge)。

challenge表示图形验证码中显示的内容,response表示正确的答案

  1. def generate_key(cls, generator=None):
  2. challenge, response = captcha_settings.get_challenge(generator)()
  3. store = cls.objects.create(challenge=challenge, response=response)
  4. return store.hashkey

相关文档

https://pypi.org/project/django-simple-captcha/
http://django-simple-captcha.readthedocs.org/en/latest/