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
{
"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>
实现这一点的一种方法是实现^{} Challenger 接口。下面的解决方案利用了^{} 中的WebOb异常可以用作WSGI应用程序这一事实。下面的示例显示了如何在假设的Facebook插件中使用它,其中2.x API允许用户而不是授予对其电子邮件的访问权限,这可能是成功注册/身份验证所必需的:
这里的一个中心点是
response
,一个webob.exc.WSGIHTTPException
的子类的实例,被用作WSGI应用程序,但是如果response
的body
属性被设置,那么它就不是自动生成的,这是我们用来显式地将响应的主体设置为字典的JSON格式的字符串表示的事实。如果在处理对以“.json”结尾的URL或Accept
头包含application/json
的请求期间调用上述质询程序,则响应的主体可能呈现如下形式:如果不是,则正文将呈现为HTML:
相关问题 更多 >
编程相关推荐