2014-05-22 30 views
0

所以我知道你可以在GAE從繼承的類內webapp2.RequestHanlder使用這種重定向:應用程序引擎:如何從一個類之外重定向

class Foo(webapp2.RequestHandler): 
    def get(self): 
     self.redirect('https://google.com') 

雖然這個作品,這將是偉大的,是能夠在課堂外進行重定向。

例如,假設你有下面的代碼是一個全球性的功能 - 也就是說,它並不存在於內側的一類:

def fetch_url(url, method=urlfetch.GET, data=''): 
    """Send a HTTP request""" 

    result = urlfetch.fetch(url=url, method=method, payload=data, 
          headers={'Access-Control-Allow-Origin': '*'}) 

    return result.content 

如果你可以從功能重定向,你可以檢查狀態碼並重定向到錯誤頁面。例如。

if result.status_code != 200: 
    urllib2.urlopen('/error_page.html') 
    return 

不幸的是,上面的代碼在GAE中沒有做任何事情,並且會生成以下警告。

WARNING 2014-05-22 21:58:24,364 urlfetch_stub.py:482] Stripped prohibited headers from URLFetch request: ['Host'] 

那麼有沒有辦法在類之外執行重定向?

回答

1

你可以讓你自己的Exception子類來處理重定向。

我這樣做是爲了使自己的webapp2.RequestHandler子類覆蓋handle_exception方法(See the docs

class RedirectError(Exception): 
    def __init__(self, new_url): 
     self.new_url = new_url 

class MyWebappFramework(webapp2.RequestHandler): 
    def handle_exception(self, exception, debug_mode): 
     if isinstance(exception, RedirectError): 
      self.redirect(exception.new_url) 
     else: 
      super(MyWebappFramework, self).handle_exception(exception, debug_mode) 

使用此功能的方式,你其實可以做一個大範圍的自定義異常輕鬆地管理預期的。例如,您也可以創建一個NotFound例外,以將狀態代碼設置爲404並呈現「頁面未找到」消息。

要使重定向發生,請提高RedirectError

就像raise RedirectError("http://www.google.com")一樣簡單。

+0

爲了好玩,這裏有一些錯誤,我已經實現了:''[NotFoundError,LoginRequiredError,LoginUnderPrivileged,ForbiddenError,RedirectError]'' – Josh

+0

所以我得到這個,當我執行你的代碼: 文件「/用戶/ bengrunfeld /桌面/Work/code/wf-ghconsole/console/auth.py「,第53行,在fetch_url中 raise RedirectError(」http://www.google.com「) RedirectError INFO 2014-05-22 22:49: 38,562 module.py:639]默認:「GET/HTTP/1.1」500 228 任何想法? – Ben

+0

是@BenGrunfeld,請求的處理程序是「MyWebappFramework」的子類嗎?如果不是,''handle_exception''方法將不會被連接以捕獲異常。 換句話說,fetch_url是否會調用回溯到「MyWebappFramework」子類? – Josh

相關問題