2015-06-30 28 views
7

我的金字塔應用程序處理了一些URL。當非授權用戶試圖打開任何URL,然後將用戶重定向到登錄窗體:金字塔中的不同登錄視圖

def forbidden(request): 
    if request.user.keyname == 'guest': 
     return HTTPFound(location=request.route_url('auth.login',)) 

    request.response.status = 403 
    return dict(subtitle=u"Access denied") 

config.add_view(forbidden, context=HTTPForbidden, renderer='auth/forbidden.mako') 

但對於某些URL(路由)我要回到沒有登錄表單,但WWW-Authenticate頭一個401 Unauthorized status code。我如何設置我的路線來完成這個?我猜我必須使用route_predicate

+2

爲什麼你不能簡單地返回HTTPUnauthorized,如[這裏](http://docs.pylonsproject.org/projects/pyramid//en/latest/narr/views.html#http-exceptions)所述的幾個視圖那需要這個邏輯? –

回答

4

您可以將這兩個錯誤包裝到您的自定義錯誤中,並提出這兩個錯誤。然後,您可以處理您的異常並針對每個錯誤運行所需的方案。這裏有一個例子:

class YourError(HTTPException): 
    def __init__(self, error): 
     super(YourError, self).__init__() 

     self.error = error 

    def handle(self, request): 
     if error is HTTPForbidden or is instance(error, HTTPForbidden): 
      return self._handle403(request) 
     elif error is HTTPUnauthorized or is instance(error, HTTPUnauthorized): 
      return self._handle401(request) 

    def _handle403(self, request): 
     # do your stuff for 403 

    def _handle401(self, request): 
     # do your stuff for 401 

# ...modify your view 
def forbidden(context, request): 
    return context.handle(request) 

然後編輯您的視圖配置:

config.add_view(forbidden, context=YourError, renderer='auth/forbidden.mako') 

然後在你需要返回403401其他意見,走這條路:

def another_view(request) 
    ... 
    raise YourError(HTTPForbidden) 
    # or 
    raise YourError(HTTPUnauthorized) 
    ... 

那麼你只需要在YourError類中實現你的處理邏輯。

1

我碰到一些discussion on the Pyramid issues list,看起來它可能會解決這個問題。

這就是說,我認爲你可以做的是使用hooks覆蓋禁止視圖並創建一個自定義異常處理程序。然後在那裏,我認爲你可以區分403401錯誤,並重定向/顯示適當的響應消息,然後根據需要自定義響應。