gpt4 book ai didi

python - DeprecationWarning : BaseException. 消息已从 Python 2.6 exception.__class__, exception.message,

转载 作者:太空狗 更新时间:2023-10-29 18:16:29 26 4
gpt4 key购买 nike

谁能告诉我在这个 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,

最佳答案

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

因此,将 message 更改为 args(如果您需要所有参数)或 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

关于python - DeprecationWarning : BaseException. 消息已从 Python 2.6 exception.__class__, exception.message,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13063212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com