[英]Return HTTP status code 201 in flask
We're using Flask for one of our API's and I was just wondering if anyone knew how to return a HTTP response 201?我们将 Flask 用于我们的 API 之一,我只是想知道是否有人知道如何返回 HTTP 响应 201?
For errors such as 404 we can call:对于 404 等错误,我们可以调用:
from flask import abort
abort(404)
But for 201 I get但是对于 201 我得到
LookupError: no exception for 201 LookupError: 201 也不例外
Do I need to create my own exception like this in the docs?我是否需要在文档中像这样创建自己的异常?
You can use Response to return any http status code.您可以使用 Response 返回任何 http 状态代码。
> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')
As lacks suggested send status code in return statement and if you are storing it in some variable like由于缺少建议在 return 语句中发送状态代码,并且如果您将它存储在某个变量中,例如
notfound = 404
invalid = 403
ok = 200
and using并使用
return xyz, notfound
than time make sure its type is int not str.比时间确保它的类型是 int 不是 str。 as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html当我遇到这个小问题时,这里也是全球遵循的状态代码列表http://www.w3.org/Protocols/HTTP/HTRESP.html
Hope it helps.希望能帮助到你。
In your flask code, you should ideally specify the MIME type as often as possible, as well:在您的烧瓶代码中,理想情况下,您还应该尽可能多地指定 MIME 类型:
return html_page_str, 200, {'ContentType':'text/html'}
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
...etc ...等等
you can also use flask_api for sending response您还可以使用 flask_api 发送响应
from flask_api import status
@app.route('/your-api/')
def empty_view(self):
content = {'your content here'}
return content, status.HTTP_201_CREATED
you can find reference here http://www.flaskapi.org/api-guide/status-codes/你可以在这里找到参考http://www.flaskapi.org/api-guide/status-codes/
Ripping off Luc's comment here , but to return a blank response, like a 201
the simplest option is to use the following return in your route. 在此处删除Luc 的评论,但要返回空白响应,例如201
,最简单的选择是在您的路由中使用以下返回值。
return "", 201
So for example:例如:
@app.route('/database', methods=["PUT"])
def database():
update_database(request)
return "", 201
Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created.根据 API 的创建方式,通常使用 201(已创建)返回已创建的资源。 For example if it was creating a user account you would do something like:例如,如果它正在创建一个用户帐户,您将执行以下操作:
return {"data": {"username": "test","id":"fdsf345"}}, 201
Note the postfixed number is the status code returned.注意后缀数是返回的状态码。
Alternatively, you may want to send a message to the client such as:或者,您可能希望向客户端发送消息,例如:
return {"msg": "Created Successfully"}, 201
In my case I had to combine the above in order to make it work就我而言,我必须结合上述内容才能使其工作
return Response(json.dumps({'Error': 'Error in payload'}),
status=422,
mimetype="application/json")
So, if you are using flask_restful
Package for API's returning 201 would becomes like因此,如果您使用flask_restful
Package 来获取API 的返回值201 会变成这样
def bla(*args, **kwargs):
...
return data, 201
where data
should be any hashable/ JsonSerialiable value, like dict, string.其中data
应该是任何可散列/ JsonSerialiable 值,如字典、字符串。
for error 404 you can对于错误 404,您可以
def post():
#either pass or get error
post = Model.query.get_or_404()
return jsonify(post.to_json())
for 201 success 201 成功
def new_post():
post = Model.from_json(request.json)
return jsonify(post.to_json()), 201, \
{'Location': url_for('api.get_post', id=post.id, _external=True)}
You just need to add your status code after your returning data like this:您只需要在返回数据后添加状态代码,如下所示:
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()
It's a basic flask project.这是一个基本的烧瓶项目。 After starting it and you will find that when we request http://127.0.0.1:5000/
you will get a status 201 from web broswer console.启动后,您会发现当我们请求http://127.0.0.1:5000/
您将从 Web 浏览器控制台获得状态 201。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.