Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在非返回函数中引发重定向_Python_Django_Error Handling - Fatal编程技术网

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: /