我们正在使用Flask为我们的API之一,我只是想知道是否有人知道如何返回HTTP响应201?

对于404这样的错误,我们可以调用:

from flask import abort
abort(404)

但是201美元我得到了

LookupError: 201没有例外

我需要在文档中创建自己的异常吗?


当前回答

你可以在这里阅读。

return render_template('page.html'), 201

其他回答

你只需要在你返回的数据后添加你的状态码,就像这样:

from flask import Flask

app = Flask(__name__)
@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!',201
if __name__ == '__main__':
    app.run()

这是一个基本的烧瓶项目。启动后,您会发现当我们请求http://127.0.0.1:5000/时,您将从web浏览器控制台获得状态201。

你可以在这里阅读。

return render_template('page.html'), 201

返回语句中缺少建议的发送状态代码 如果你把它存储在某个变量中

notfound = 404
invalid = 403
ok = 200

和使用

return xyz, notfound

当我遇到这个小问题时,请确保它的类型是int而不是str 此外,这里是状态代码的列表遵循全局 http://www.w3.org/Protocols/HTTP/HTRESP.html

希望能有所帮助。

在你的flask代码中,理想情况下,你应该尽可能多地指定MIME类型,以及:

return html_page_str, 200, {'ContentType':'text/html'}

return json.dumps({'success':True}), 200, {'ContentType':'application/json'}

您可以使用Response来返回任何http状态代码。

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')