2015-07-20 67 views
1

在我WERKZEUG的应用程序,我拦截所有的错误响应并尝试如果客户希望JSON与JSON响应响应或404或500返回通常的HTML页面:如何确定客户端需要一个JSON响应

def handle_error_response(self, environ, start_response, exc): 
    if ('application/json' in environ.get('CONTENT_TYPE', '') 
      and exc.get_response().content_type != 'application/json'): 
     start_response('%s %s' % (exc.code, exc.name), 
         (('Content-Type', 'application/json'),)) 
     return (json.dumps({"success": False, "error": exc.description}, ensure_ascii=False),) 
    # go the regular path 
    ... 

在此解决方案中,我依靠Content-Type标题包含字符串'application/json'

然而,这看起来并不像一个正确的解决方案,因为维基百科说:

的Content-Type MIME类型的请求主体的(使用POST和PUT请求)

检查'text/html'是否在标头Accept内,然后返回HTML响应,否则返回JSON响应是否是一个好策略?

还有其他更强大的解决方案吗?

当铬请求一个HTML页头

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 

被发送,当灰烬进行API请求

Accept: application/json, text/javascript, */*; q=0.01 

被发送。

也许应该考虑X-Requested-With: XMLHttpRequest

回答

0

您应该添加AcceptMixin到您的请求对象。

一旦你这样做了,你可以在你的请求对象上使用accept_mimetypes.accept_json,accept_mimetypes.accept_htmlaccept_mimetypes.accept_xhtml属性。响应的默认内容类型实际上仅取决于您的应用程序的内容;试试想象哪个会导致更少的混淆。

+0

感谢您提供关于'AcceptMixin'的提示,但我的问题是如何使用'AcceptMixin.accept_mimetypes'提供的信息。当Chrome请求HTML页面'HTTP_ACCEPT'时:当Ember创建API时,会发送'text/html,application/xhtml + xml,application/xml; q = 0.9,image/webp,*/*; q = 0.8'请求''HTTP_ACCEPT':'application/json,text/javascript,*/*; q = 0.01''被发送。在这两种情况下'request.accept_mimetypes.accept_json' == request.accept_mimetypes.accept_html' =='True'。 – warvariuc

0

这是为我们工作:

if ('text/html' not in environ.get('HTTP_ACCEPT', '') 
      and 'application/json' not in response.content_type): 
     # the user agent didn't explicitely request html, so we return json 
     ... # make the JSON response 

即如果客户希望html - 不要返回json。否则返回 json响应,如果响应尚未json。