Flask:如何在响应中设置状态代码

Mr.*_*ent 3 python http-status-codes flask

一切运行良好,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
Run Code Online (Sandbox Code Playgroud)

。

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
Run Code Online (Sandbox Code Playgroud)

如何将状态代码设置为其他内容?

小智 6

这应该回答您的问题: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
Run Code Online (Sandbox Code Playgroud)