我正在编写一个repoze.who
插件repoze.who
,并希望从身份验证中间件返回 JSON并仍然控制 HTTP 状态代码。如何才能做到这一点?
1 回答
1
实现此目的的一种方法是实现repoze.who
Challenger接口。以下解决方案利用了WebOb异常 inwebob.exc
可用作 WSGI 应用程序这一事实。以下示例显示了如何在假设的 Facebook 插件中使用此功能,其中2.x API允许用户不授予对其电子邮件的访问权限,这可能是成功注册/身份验证所必需的:
import json
from webob.acceptparse import MIMEAccept
from webob.exc import HTTPUnauthorized, HTTPBadRequest
FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED = 'repoze.who.facebook_connect.not_granted'
class ExampleJSONChallengerPlugin(object):
json_content_type = 'application/json'
mime_candidates = ['text/html',
'application/xhtml+xml',
json_content_type,
'application/xml',
'text/xml']
def is_json_request_env(self, environ):
"""Checks whether the current request is a json request as deemed by
TurboGears (i.e. response_type is already set) or if the http
accept header favours 'application/json' over html.
"""
if environ['PATH_INFO'].endswith('.json'):
return True
if 'HTTP_ACCEPT' not in environ:
return False
# Try to mimic what Decoration.lookup_template_engine() does.
return MIMEAccept(environ['HTTP_ACCEPT']) \
.best_match(self.mime_candidates) is self.json_content_type
def challenge(self, environ, status, app_headers, forget_headers):
if FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED in environ:
response = HTTPBadRequest(detail={
'not_granted':
environ.pop(FACEBOOK_CONNECT_REPOZE_WHO_NOT_GRANTED),
})
elif status.startswith('401 '):
response = HTTPUnauthorized()
else:
response = None
if response is not None and self.is_json_request_env(environ):
response.body = json.dumps({
'code': response.code,
'status': response.title,
'explanation': response.explanation,
'detail': response.detail,
})
response.content_type = self.json_content_type
return response
这里的一个中心点是response
,一个子类的实例webob.exc.WSGIHTTPException
,被用作 WSGI 应用程序,而且如果设置了response
的body
属性,那么它不会自动生成,这是我们用来显式设置响应正文的事实到我们字典的 JSON 格式的字符串表示。Accept
如果在处理对以 '.json' 结尾的 URL 或标头 include的请求时调用了上述挑战者application/json
,则响应的正文可能呈现为:
{
"status": "Bad Request",
"explanation": "The server could not comply with the request since it is either malformed or otherwise incorrect.",
"code": 400,
"detail": {"not_granted": ["email"]}
}
如果不是,则正文将呈现为 HTML:
<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>400 Bad Request</h1>
The server could not comply with the request since it is either
malformed or otherwise incorrect.<br /><br />
{'not_granted': [u'email']}
</body>
</html>
于 2015-04-16T11:59:36.277 回答