在我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
?
感谢您提供关于'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