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)
    7. def save(self, *args, **kwargs):
    8. self.response = self.response.lower()
    9. if not self.expiration:
    10. self.expiration = timezone.now() + datetime.timedelta(
    11. minutes=int(captcha_settings.CAPTCHA_TIMEOUT)
    12. )
    13. if not self.hashkey:
    14. key_ = (
    15. smart_text(randrange(0, MAX_RANDOM_KEY))
    16. + smart_text(time.time())
    17. + smart_text(self.challenge, errors="ignore")
    18. + smart_text(self.response, errors="ignore")
    19. ).encode("utf8")
    20. self.hashkey = hashlib.sha1(key_).hexdigest()
    21. del key_
    22. super(CaptchaStore, self).save(*args, **kwargs)
    23. def __str__(self):
    24. return self.challenge
    25. def remove_expired(cls):
    26. cls.objects.filter(expiration__lte=timezone.now()).delete()
    27. remove_expired = classmethod(remove_expired)
    28. @classmethod
    29. def generate_key(cls, generator=None):
    30. challenge, response = captcha_settings.get_challenge(generator)()
    31. store = cls.objects.create(challenge=challenge, response=response)
    32. return store.hashkey