Pyt*_*Dev 10 python exception python-2.6 deprecation-warning
任何人都可以告诉我这个Django中间件警告背后的实际原因,我该如何解决这个问题?
我收到此消息" DeprecationWarning:BaseException.message自Python 2.6异常以来已被弃用.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,
Run Code Online (Sandbox Code Playgroud)
aba*_*ert 26
如果我没记错的话,当Python在2.5(?)中切换到新的raise语法时,他们摆脱了message成员而支持args元组.为了向后兼容,BaseException.message实际上是相同的BaseException.args[0] if BaseException.args else None,但是你不应该在新代码中使用它.
因此,改变message要么args(如果你希望所有参数)或args[0](或者,如果你担心有可能是无参数,即防止发烧友版()),这取决于你想要的.
这样做的原因的变化是,新风格的例外,没有魔法raise或except不再; 你只是在raise语句中调用异常类的构造函数,并在语句中的变量中捕获异常except.所以:
try:
raise MyException('Out of cheese error', 42)
except Exception as x:
print x.args
Run Code Online (Sandbox Code Playgroud)
这将打印('Out of cheese error', 42).如果你print x.message只是得到了你'Out of cheese error'.因此,可以简化以前必须执行奇特事物以将错误代码作为单独成员等进行处理的Exception子类; 事实上,整个事情归结为:
class BaseException(object):
def __init__(self, *args):
self.args = args
Run Code Online (Sandbox Code Playgroud)