Python 在非返回函数中引发重定向
我有一个函数不返回,我想通过引发异常进行重定向 我有以下代码:Python 在非返回函数中引发重定向,python,django,error-handling,Python,Django,Error Handling,我有一个函数不返回,我想通过引发异常进行重定向 我有以下代码: class RedirectRequired(Exception): def __init__(self, url): self.url = url 以及功能 def Foo(x): hede = {'hodo':5} try: hede.get('hodo').get('hede') except AttributeError, e: lo
class RedirectRequired(Exception):
def __init__(self, url):
self.url = url
以及功能
def Foo(x):
hede = {'hodo':5}
try:
hede.get('hodo').get('hede')
except AttributeError, e:
logger.error(e.message)
raise RedirectRequired('/')
但是有错误没有提供异常
。有没有像下面这样重定向或引发异常的想法
也有错误
提交消息时出错:u'RedirectRequired'
提交消息时出错:u'RedirectRequired'问题是
RedirectRequired
异常的构造函数构造了一个RedirectRequired
异常来引发它,它构造了一个RedirectRequired
异常来引发它,它
每次通过这个无限递归,您都会记录e.message
,每次都是相同的消息
大约1000次之后,您将遇到一个运行时错误:超过了最大递归深度
这里最可能需要的是两件事:RedirectRequired
异常类型和使用它的Redirector
包装类或redirect
包装函数。像这样:
class RedirectRequired(Exception):
pass
class Redirector(object):
def __init__(self, url):
self.url = url
hede = {'hodo':5}
try:
hede.get('hodo').get('hede')
except AttributeError, e:
logger.error(e.message)
raise RedirectRequired('/')
现在:
r=重定向器('abc')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第8行,在_init中__
__所需的主重定向:/
这不会引发异常,因为假设hede
是一个字典或类似的问题,则hede.get
不会引发AttributeError
。这只是一个样本。获取属性错误的过程要长得多,而这段代码的位置是-在某些视图中
?如果您仍然使用.get
,它不会改变任何东西。不过,您要说的是,您一定会得到一个AttributeError
?验证这一点。作为旁注,除非您确实需要使用2.6之前的较旧Python版本,否则您应该使用除AttributeError外的As e:
,而不是除AttributeError外的e:
。它避免了各种歧义,使linters感到高兴,使您的代码与Python3.x兼容,等等。我正在纠正它。谢谢你的回复
>>> r = Redirector('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __init__
__main__.RedirectRequired: /