在flask中返回HTTP状态码201

发布于 2024-12-10 23:00:02 字数 352 浏览 0 评论 0原文

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

对于 404 之类的错误,我们可以调用:

from flask import abort
abort(404)

但是对于 201 我得到

LookupError:201也不例外

我是否需要创建自己的异常,例如 this在文档中?

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?

For errors such as 404 we can call:

from flask import abort
abort(404)

But for 201 I get

LookupError: no exception for 201

Do I need to create my own exception like this in the docs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

单调的奢华 2024-12-17 23:00:02

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

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

You can use Response to return any http status code.

> from flask import Response
> return Response("{'a':'b'}", status=201, mimetype='application/json')
熟人话多 2024-12-17 23:00:02

您可以在此处阅读相关内容。

return render_template('page.html'), 201

You can read about it here.

return render_template('page.html'), 201
楠木可依 2024-12-17 23:00:02

您可以这样做

result = {'a': 'b'}
return result, 201

如果您想在响应中返回 JSON 数据以及错误代码,
您可以在此处此处了解 make_response API 详细信息

You can do

result = {'a': 'b'}
return result, 201

if you want to return a JSON data in the response along with the error code
You can read about responses here and here for make_response API details

烟花易冷人易散 2024-12-17 23:00:02

由于返回语句中缺少建议的发送状态代码
如果您将其存储在某个变量中,例如

notfound = 404
invalid = 403
ok = 200

使用

return xyz, notfound

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

希望有帮助。

As lacks suggested send status code in return statement
and if you are storing it in some variable like

notfound = 404
invalid = 403
ok = 200

and using

return xyz, notfound

than time make sure its type is int not str. as I faced this small issue
also here is list of status code followed globally
http://www.w3.org/Protocols/HTTP/HTRESP.html

Hope it helps.

故人如初 2024-12-17 23:00:02

在您的 Flask 代码中,理想情况下您还应该尽可能多地指定 MIME 类型:

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

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

...等

In your flask code, you should ideally specify the MIME type as often as possible, as well:

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

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

...etc

安人多梦 2024-12-17 23:00:02

抄袭Luc的在此处评论,但返回空白响应,例如201 最简单的选项是在路由中使用以下返回。

return "", 201

例如:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201

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.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201
野却迷人 2024-12-17 23:00:02

您还可以使用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

您可以在这里找到参考 http://www.flaskapi .org/api-guide/status-codes/

you can also use flask_api for sending response

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/

简美 2024-12-17 23:00:02

就我而言,我必须将上述内容结合起来才能使其发挥作用

return Response(json.dumps({'Error': 'Error in payload'}), 
status=422, 
mimetype="application/json")

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")
自由如风 2024-12-17 23:00:02

根据 API 的创建方式,通常使用 201(已创建),您将返回已创建的资源。例如,如果它正在创建一个用户帐户,您将执行以下操作:

return {"data": {"username": "test","id":"fdsf345"}}, 201

请注意,后缀数字是返回的状态代码。

或者,您可能想向客户端发送消息,例如:

return {"msg": "Created Successfully"}, 201

Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. 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
残龙傲雪 2024-12-17 23:00:02

对于错误 404,您可以获得

def post():
    #either pass or get error 
    post = Model.query.get_or_404()
    return jsonify(post.to_json())

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)}

for error 404 you can

def post():
    #either pass or get error 
    post = Model.query.get_or_404()
    return jsonify(post.to_json())

for 201 success

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)}
ゃ懵逼小萝莉 2024-12-17 23:00:02

您只需在返回数据后添加状态代码,如下所示:

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()

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

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.

清欢 2024-12-17 23:00:02

因此,如果您使用 API 的 flask_restful
返回 201 会变得像

def bla(*args, **kwargs):
    ...
    return data, 201

其中 data 应该是任何可散列/ JsonSerialable 值,如字典、字符串。

So, if you are using flask_restful Package for API's
returning 201 would becomes like

def bla(*args, **kwargs):
    ...
    return data, 201

where data should be any hashable/ JsonSerialiable value, like dict, string.

冷…雨湿花 2024-12-17 23:00:02

根据最新的 Flask 版本 3.0.2 使用类似的内容

return render_template('main.html', status=201, data=data)#where main.html 是模板名称,data 是要传递给模板的变量

Use something like this as per latest flask version 3.0.2

return render_template('main.html', status=201, data=data)#where main.html is template name and data is variables to be passed to the template

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文