我正在尝试构建一个系统,让用户能够定义和测试自己的regex模式。为此,我有以下设置:
import re
class ExtendedRegexValidator(models.Model):
pattern = models.TextField(
_('pattern'),
help_text=_('Required. Must be a valid regular expression pattern.')
)
def save(self, *args, **kwargs):
try:
re.compile(self.pattern)
except Exception as e:
# handle exception
super(ExtendedRegexValidator, self).save(*args, **kwargs)
在保存之前,我尝试使用模型的pattern
字段的值编译regex模式,该字段是TextField
。这真的有必要吗?有没有更理想的方法?这感觉有点不舒服。
谢谢
是的,验证是必要的,因为有一些有效的字符串不是有效的正则表达式。参见^{} 上的Python文档:
其他人建议改为在表单提交期间进行验证,但为了数据完整性,我认为您在模型层进行验证是正确的。在处理
re.error
时,可以在表单提交层引发ValidationError
您的验证代码符合Python的EAFP哲学:
我也看不到任何内置的方式来验证字符串作为regex模式而不尝试使用或编译它。但是,我建议为regex模式创建一个custom model field,这样您就可以封装这个验证,并可能在其他模型中重用这个功能
相关问题 更多 >
编程相关推荐