我有一个带有简单验证码的python/django应用程序。 简单的验证码是根据一些算法出现的。你知道吗
有两个几乎相同的构造函数。区别就在于继承。 如何避免代码重复?你知道吗
class PostCaptchaForm(PostForm):
captcha = CaptchaField()
def __init__(self, *args, **kwargs):
self.request = kwargs['request']
del kwargs['request']
super(PostCaptchaForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(PostCaptchaForm, self).clean()
success = self.is_valid()
utils.update_captcha_access(self.request, success)
if success:
return cleaned_data
else:
raise forms.ValidationError("captcha validation failed")
class ThreadCaptchaForm(ThreadForm):
captcha = CaptchaField()
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(ThreadCaptchaForm, self).__init__(*args, **kwargs)
def clean(self):
cleaned_data = super(ThreadCaptchaForm, self).clean()
success = self.is_valid()
utils.update_captcha_access(self.request, success)
if success:
return cleaned_data
else:
raise forms.ValidationError("captcha validation failed")
我会用多重继承来实现,用一个基本的captcha表单作为mixin,与ThreadForm或PostForm一起使用
相关问题 更多 >
编程相关推荐