10

谁能告诉我在这个 Django 中间件中收到警告背后的实际原因,我该如何解决这个问题?

我收到这条消息“ DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 exception.class , exception.message ,

class GeneralMiddleware(object):
    def process_exception(self, request, exception):
        if exception.__class__ is SandboxError:
            # someone is trying to access a sandbox that he has no
            # permission to
            return HttpResponseRedirect("/notpermitted/")

        exc_type, value, tb = sys.exc_info()
        data = traceback.format_tb(
                    tb, None) + traceback.format_exception_only(
                    exc_type, value)
        msg = (
            "Failure when calling method:\n"
            u"URL:'%s'\nMethod:'%s'\nException Type:'%s'\n"
            u"Error Message '%s'\nFull Message:\n%s"
            % (request.get_full_path(), request.method,
               exception.__class__, exception.message,
4

2 回答 2

28

如果我没记错的话,当 Python 在 2.5(?)中切换到新的 raise 语法时,他们摆脱了message成员,转而使用args元组。为了向后兼容,BaseException.message实际上与 . 相同BaseException.args[0] if BaseException.args else None,但您不应该在新代码中使用它。

因此,根据您的需要,更改messageargs(如果您想要所有参数)或args[0](或者,如果您担心可能没有参数,则可以使用更高级的版本来防止 args ())。

这种变化的原因是,有了新式的例外,就没有魔法raiseexcept。您只是在语句中调用异常类的构造函数raise,并在语句中的变量中捕获异常except。所以:

try:
  raise MyException('Out of cheese error', 42)
except Exception as x:
  print x.args

这将打印('Out of cheese error', 42). 如果你只有print x.message你就会得到'Out of cheese error'. 因此,过去必须做一些花哨的事情才能将错误代码作为单独的成员等携带的 Exception 子类可以被简化;事实上,整个事情归结为:

class BaseException(object):
  def __init__(self, *args):
    self.args = args
于 2012-10-25T07:46:42.950 回答
0

你的SandboxError类是从类继承的Exception吗?如果没有,您将收到此消息。推理在PEP352中描述。

在代码中,您的异常应该这样定义:

class SandboxException(Exception):
    ....
于 2012-10-25T07:06:28.523 回答