2017-07-30 151 views
1

在燒瓶文檔中有一個鉤子函數的示例,當沒有找到瓶子定義的URL端點時,可以通過調用來爲url_for函數添加自定義行爲。如果沒有匹配的用戶定義的URL端點,程序員可以添加自定義端點或重新引發異常(使用原始上下文)。python2與python3 raise語句

def external_url_handler(error, endpoint, values): 
    "Looks up an external URL when `url_for` cannot build a URL." 
    # This is an example of hooking the build_error_handler. 
    # Here, lookup_url is some utility function you've built 
    # which looks up the endpoint in some external URL registry. 
    url = lookup_url(endpoint, **values) 
    if url is None: 
     # External lookup did not have a URL. 
     # Re-raise the BuildError, in context of original traceback. 
     exc_type, exc_value, tb = sys.exc_info() 
     if exc_value is error: 
      raise exc_type, exc_value, tb 
     else: 
      raise error 
    # url_for will use this result, instead of raising BuildError. 
    return url 

app.url_build_error_handlers.append(external_url_handler) 

該代碼段似乎是python2代碼和失敗的,因爲raise exc_type, exc_value, tb行python3。 python2python3文檔列出了raise語句的不同參數。

將此片段轉換爲python3的正確方法是什麼?

+1

等價的Py3代碼是'raise exc_type(exc_value).with_traceback(tb)' – AChampion

回答

0

這在文件中指定了the raise statement

您可以創建一個例外,並使用with_traceback()例外方法(該方法返回相同異常實例設置自己的回溯一步到位,其回溯設爲其參數),就像這樣:

raise Exception("foo occurred").with_traceback(tracebackobj) 

所以,你的情況,這將是:

raise exc_type(exc_value).with_traceback(tb)