【问题标题】:Flask: How do I set the status code in ResponseFlask:如何在响应中设置状态码
【发布时间】:2020-04-20 22:40:33
【问题描述】:

一切运行良好,API(flask) 很好地返回数据。但是,当我尝试自定义响应代码时,我做不到。
以下是我尝试过的两种方法:

from flask import make_response
dictionary = {1:'a', 2:'b'}
resp = make_response(dictionary,1001)
return resp

#In developer tools, I could see the data, but status-code is 200

.

from flask import Response
dictionary = {1:'a', 2:'b'}
resp = Response(dictionary, status = 1001)
return resp

#Here again, I see the data, but the status code is 200

如何将状态码设置为别的?

【问题讨论】:

  • 试试:return Response("{1:'a', 2:'b'}", status=201, mimetype='application/json') .Btw,1001 不是有效的 HTTP 状态码
  • 这里是 HTTP 状态代码 en.wikipedia.org/wiki/List_of_HTTP_status_codes 的参考。
  • @T.MLuan Thaks 感谢您的回复,先生。如果我想设置自定义状态码,我该怎么做?就像我想根据返回类型触发不同的操作一样。

标签: python flask http-status-codes


【解决方案1】:

这应该回答你的问题:https://flask.palletsprojects.com/en/1.1.x/quickstart/#about-responses

来自文档的示例:

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp

【讨论】:

  • 我将答案更改为更准确。最初的答案是对烧瓶 api 的引用,这与您的常规烧瓶不同。如果有人需要,请在此处留下烧瓶 api 的链接:flaskapi.org/api-guide/status-codes
  • 您可以在答案本身中添加您所做的更改,无需发表评论:)
  • 我做了,只是想确保没有人感到困惑:)
  • 感谢您的回复,先生们。我可以返回 204 以获取任何内容,但请求成功。如果我想返回自己的状态码,是否可以这样做?只是对此感到好奇。
猜你喜欢
  • 2021-07-21
  • 2021-04-28
  • 1970-01-01
  • 2015-04-20
  • 2016-11-21
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-09
相关资源
最近更新 更多