Django对象的TextField值不能编译为regex模式吗?

2024-09-29 19:35:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个系统,让用户能够定义和测试自己的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。这真的有必要吗?有没有更理想的方法?这感觉有点不舒服。 谢谢


Tags: 用户importselfre定义modelssave系统
1条回答
网友
1楼 · 发布于 2024-09-29 19:35:36

Is this actually necessary?

是的,验证是必要的,因为有一些有效的字符串不是有效的正则表达式。参见^{}上的Python文档:

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching.

其他人建议改为在表单提交期间进行验证,但为了数据完整性,我认为您在模型层进行验证是正确的。在处理re.error时,可以在表单提交层引发ValidationError

Is there a more ideal way to do this? This kinda feels hacky.

您的验证代码符合Python的EAFP哲学:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

我也看不到任何内置的方式来验证字符串作为regex模式而不尝试使用或编译它。但是,我建议为regex模式创建一个custom model field,这样您就可以封装这个验证,并可能在其他模型中重用这个功能

相关问题 更多 >

    热门问题