我正在使用Pylons并想要添加一些中间件,以便它捕获 401状态代码并使 HTTP重定向(302)到登录页面。
我知道Pylons中有内置的StatusCodeRedirect以类似的方式运行,但它不会产生HTTP重定向,而是在内部重定向 (这是我不想要的)。 / p>
是否需要添加任何现有中间件,或者是否可以轻松修改任何通用中间件以对特定状态代码进行HTTP重定向?
答案 0 :(得分:1)
这应该让你非常接近我没有测试它,但它松散地基于我写的东西,我正在使用,所以必要时调整。
from webob.dec import wsgify
class Catch401AndRedirect(object):
"""
responds to 401 redirects to signin page
"""
def __init__(self, app, signin_url):
self._app = app
self._signin_url = signin_url
@wsgify
def __call__(self, request):
response = request.get_response(self._app)
if response.status_int == 401:
response.headers["Location"] = self._signin_url
response.status_int = 302
else:
return response
编辑:忘了提这个解决方案需要webob,但由于你已经使用了pylons,你就有了这种依赖。
答案 1 :(得分:1)
最后。 我已经实现了我自己的中间件类,它使用了 pylons.util
的调用__ 的 call_wsgi_application 辅助函数from pylons.util import call_wsgi_application
class StatusCodeHTTPRedirect(object):
def __init__(self, wsgi_app, codes, redirect_to):
self.app = wsgi_app
# Transform codes to str for comparison
self.codes = tuple([str(x) for x in codes])
self.redirect_to = redirect_to
def __call__(self, environ, start_response):
status, headers, app_iter, exc_info = call_wsgi_application(self.app,
environ, catch_exc_info=True)
if status[:3] in self.codes:
start_response('302 Found', [('Location', self.redirect_to)])
return []
start_response(status, headers, exc_info)
return app_iter
希望这会有所帮助
答案 2 :(得分:0)
您可以使用完整的身份验证和Pylons授权库。最受欢迎的两个是:AuthKit和repoze.who。他们已经实现了你想做的事情。
如果您不想使用现有库,则可以编写自定义中间件。它只是一个Python可调用的f(environ, start_response)
,它处理在环境中保存的请求数据。查看config/environment.py
。