相关模块
django-simple-captcha
pip install django-simple-captcha
配置URL
先将captcha添加到url中
urlpatterns = [
path('captcha/', include('captcha.urls')),
]
该模块是如何生成图形验证码的
在生成图形验证码时,会先生成图形验证码上显示的字符challenge、正确的答案response、用来唯一表示图形验证码的hashkey、以及过期时间expiration,然后将这些数据存入数据库
class CaptchaStore(models.Model):
id = models.AutoField(primary_key=True)
challenge = models.CharField(blank=False, max_length=32)
response = models.CharField(blank=False, max_length=32)
hashkey = models.CharField(blank=False, max_length=40, unique=True)
expiration = models.DateTimeField(blank=False)
常用方法
from captcha.models import CaptchaStore
生成图形验证码
CaptchaStore.generate_key()
CaptchaStore.pick()
移除数据库中存储的过期的验证码
CaptchaStore.remove_expired()
验证图形验证码
def check_captcha(captcha_hashkey, captcha_response):
CaptchaStore.remove_expired()
try:
store = CaptchaStore.objects.get(hashkey=key)
except CaptchaStore.DoesNotExist:
# HTTP 410 Gone status so that crawlers don't index these expired urls.
return HttpResponse(status=410)
return captcha_response == store.response
获取图形验证码URL
from captcha.helpers import captcha_image_url
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表示正确的答案
def generate_key(cls, generator=None):
challenge, response = captcha_settings.get_challenge(generator)()
store = cls.objects.create(challenge=challenge, response=response)
return store.hashkey
相关文档
https://pypi.org/project/django-simple-captcha/
http://django-simple-captcha.readthedocs.org/en/latest/