gpt4 book ai didi

python - 如何确定客户端是否需要 JSON 响应

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:28:39 27 4
gpt4 key购买 nike

在我的 Werkzeug 应用程序中,如果客户端需要 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
...

在此解决方案中,我依赖于包含字符串'application/json'Content-Type header 。

但是这看起来不像是正确的解决方案,因为维基百科说:

Content-Type The MIME type of the body of the request (used with POST and PUT requests)

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

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

当 Chrome 请求 HTML 页面标题时

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

在 Ember 发出 API 请求时发送

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

已发送。

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

最佳答案

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

完成此操作后,您可以在请求对象上使用 accept_mimetypes.accept_jsonaccept_mimetypes.accept_htmlaccept_mimetypes.accept_xhtml 属性。响应的默认内容类型实际上仅取决于您的应用程序;试着想象一下哪个会导致更少的困惑。

关于python - 如何确定客户端是否需要 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31519893/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com