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

发布于 2024-08-23 10:06:30 字数 493 浏览 6 评论 0原文

我正在一个类中执行所有表单验证,并且希望能够将错误从类中获取到渲染的 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

有更好或首选的方法来执行此操作吗?

谢谢。

I'm performing all my form validation in a class, and would like to be able to get the errors from the class to the rendered html. One approach I was thinking about was to create a global variable "c" that would store all the errors and to set them from within the class, as I still want the individual methods to return false when they fail. Here is some sample code:

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

Is there a better or preferred way to do this?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

这样的小城市 2024-08-30 10:06:30

我喜欢用字典来保存错误和警告。然后我可以在表单顶部或内联显示所有错误。我还定义了 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

I like to use a dictionary to hold the errors and warnings. Then I can either show all errors at the top of the form or inline. I also define error and warning variables so I can easily tell the two apart.

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
眼中杀气 2024-08-30 10:06:30

是的,当然,我的建议是完全避免返回状态代码。

一般来说,有很多文献反对使用状态代码和全局变量来保存在 Python 等高级环境中处理错误的详细信息。
Ned Batchelder 写了一篇关于这个主题的非常好的文章;我强烈建议您阅读该页面,了解为什么异常处理通常被认为是一种更好的方法的原因列表。

但是,当我们谈论 Python 时,传达异常和错误的官方方法是通过异常处理。期间。
使用任何其他方式,都会使您的代码违背对 Python 代码的普遍期望,这意味着它将更难以阅读和维护。

Yes, definitely, and my suggestion is to avoid returning status codes at all.

Generally speaking, there is a lot of literature against using status codes and global variables to hold details for handling errors in a high level environment like Python.
Ned Batchelder has written a very good article on this topic; I strongly suggest you reading that page for a through lists of reasons why exception handling is usually considered a superior method.

But, as we are talking about Python, the official way to communicate exceptions, and errors, is through exception handling. Period.
Using any other way, will make your code against the common expectations for Python code, meaning it will be harder to read, and maintain.

各空 2024-08-30 10:06:30

在 Web 应用程序的上下文中,您只需填充 tmpl_context

from pylons import tmpl_context as c
from yourproject.lib.base import BaseController, render

class MyController(BaseController):
    def index(self):
        c.error = 'Invalid e-mail address'
        return render('/mytemplate.mako')

其中 'mytemplate.mako' 文件内容为:

% if c.error:
    error: ${c.error}
% endif

在通用 Python 代码中,您可以:

返回一个元组

您可以从函数中返回一个元组(这不是更好的方式):

class Error(Exception):
    pass

def isvalid(something):
    return False, Error("'%s' is invalid" % (something,))

示例:

ok, err = isvalid(object())
if not ok:
   print err

引发异常

如果直接调用者不应该处理函数中的错误,那么可以使用异常将有关错误的信息传递到堆栈上。

def do_stuff(something):
    if not something.isready():
       raise Error("'%s' is not ready to do stuff" % (something,))

示例:

class C(object):
    def isready(self):
        return False

def run():
    # no error handling here
    do_stuff(C()) 
    # do something else

try: run()
except Error, e:
    print e

传递回调

def do_stuff(something, onerror=lambda err: None):
    if not something.isready():
       onerror(Error("'%s' is not ready to do stuff" % (something,)))

示例:

do = lambda: do_stuff(C(), onerror=repeat)
def repeat(err):
    """Repeat until success."""
    print err
    time.sleep(5) 
    do() # possible infinite loop 
do()

In the context of a web application you could just populate tmpl_context.

from pylons import tmpl_context as c
from yourproject.lib.base import BaseController, render

class MyController(BaseController):
    def index(self):
        c.error = 'Invalid e-mail address'
        return render('/mytemplate.mako')

Where 'mytemplate.mako' file content is:

% if c.error:
    error: ${c.error}
% endif

In generic python code you can:

Return a tuple

You can return a tuple from your function (it is not preferable way):

class Error(Exception):
    pass

def isvalid(something):
    return False, Error("'%s' is invalid" % (something,))

Example:

ok, err = isvalid(object())
if not ok:
   print err

Raise an exception

If an immediate caller is not supposed to handle an error from your function then an exception can be used to pass information about the error up the stack.

def do_stuff(something):
    if not something.isready():
       raise Error("'%s' is not ready to do stuff" % (something,))

Example:

class C(object):
    def isready(self):
        return False

def run():
    # no error handling here
    do_stuff(C()) 
    # do something else

try: run()
except Error, e:
    print e

Pass callback

def do_stuff(something, onerror=lambda err: None):
    if not something.isready():
       onerror(Error("'%s' is not ready to do stuff" % (something,)))

Example:

do = lambda: do_stuff(C(), onerror=repeat)
def repeat(err):
    """Repeat until success."""
    print err
    time.sleep(5) 
    do() # possible infinite loop 
do()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文