Django 对象的 TextField 值能否编译为正则表达式模式?

Can a TextField value of a Django object fail to compile as a regex pattern?

我正在尝试构建一个系统,用户可以在其中定义和测试他们自己的正则表达式模式。为此,我有以下设置:

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 字段的值编译一个正则表达式模式,它是一个 TextField。这真的有必要吗?有没有更理想的方法来做到这一点?这有点老套。

Is this actually necessary?

是的,验证是必要的,因为会有有效的字符串不是有效的正则表达式。请参阅 Python 在 re.error 上的文档:

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.

我也没有看到任何内置方法可以在不尝试使用或编译字符串的情况下将其验证为正则表达式模式。但是,我建议为正则表达式模式创建一个 custom model field,这样您就可以封装此验证并可能在其他模型中重用该功能。