python - 在 python 中将错误从类传递到渲染的 html 的正确方法是什么

标签 python pylons mako

我正在一个类中执行所有表单验证,并且希望能够将错误从类中获取到呈现的 html。我正在考虑的一种方法是创建一个全局变量“c”来存储所有错误并在类中设置它们,因为我仍然希望各个方法在失败时返回 false。这是一些示例代码:

class User():

def add(self):

    #Check that e-mail has been completed
    try:
        #Validate e-mail address
        if (isAddressValid(self.email)):
            c.error = 'Invalid e-mail address'
            return 0
    except NameError:
        c.error = 'No e-mail address specified'
        return 0

是否有更好或首选的方法来做到这一点?

谢谢。

最佳答案

我喜欢使用字典来保存错误和警告。然后我可以在表单顶部或内联显示所有错误。我还定义了 errorwarning 变量,以便我可以轻松区分两者。

class User(object):
    def __init__(self):
        self.messages = {}

    def add(self):
        error = False
        warning = False

        #Check that name has a space
        try:
            if (self.name.find(' ') == -1):
                warning = True
                self.messages['email'] = {'type': 'warning',
                                          'msg': 'Your name has no space.'}
        except NameError:
            error = True
            self.messages['email'] = {'type': 'error',
                                      'msg': 'You have no name.'}

        #Check that e-mail has been completed
        try:
            #Validate e-mail address
            if (isAddressValid(self.email)):
                error = True
                self.messages['email'] = {'type': 'error',
                                          'msg': 'Invalid e-mail address'}
        except NameError:
            error = True
            self.messages['email'] = {'type': 'error',
                                      'msg': 'No e-mail address specified'}

        return error, warning

关于python - 在 python 中将错误从类传递到渲染的 html 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2352201/

相关文章:

python - 将 Mako 与 Pyramid 一起使用会导致错误

javascript - 如何确保脚本运行一次且仅运行一次

python - 将 Wagtail 与 Django 管理集成

python - Pylons 和 Memcached

Python学习环境

pylons - 使用 pylons 和 psycopg2 连接到远程 postgres 数据库

python - Unicode解码错误: 'ascii' codec can't decode byte 0xc5

python - Python中的Hadoop流作业失败(失败)

python - SampleRNN - Pytorch 实现初学者

python - 使用嵌套循环进行 Pandas 赋值会导致内存错误