如何在Flask上返回400(错误请求)? [英] How to return 400 (Bad Request) on Flask?

查看:156
本文介绍了如何在Flask上返回400(错误请求)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的flask应用程序,并且正在读取python的响应:

I have created a simple flask app that and I'm reading the response from python as:

response = requests.post(url,data=json.dumps(data), headers=headers ) 
data = json.loads(response.text)

现在我的问题是,在某些情况下,我想返回400或500条消息响应.到目前为止,我正在这样做:

Now my issue is that under certain conditions I want to return a 400 or 500 message response. So far I'm doing it like this:

abort(400, 'Record not found') 
#or 
abort(500, 'Some error...') 

这确实在终端上打印了消息:

This does print the messa on the terminal:

但是在API响应中,我不断收到500错误响应:

But in the API response I keept getting a 500 error response:

代码的结构如下:

|--my_app
   |--server.py
   |--main.py
   |--swagger.yml

其中server.py具有以下代码:

Where server.py has this code:

from flask import render_template
import connexion
# Create the application instance
app = connexion.App(__name__, specification_dir="./")
# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")
# Create a URL route in our application for "/"
@app.route("/")
def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return:        the rendered template "home.html"
    """
    return render_template("home.html")
if __name__ == "__main__":
    app.run(host="0.0.0.0", port="33")

main.py具有我用于API端点的所有功能.

And main.py has all the function I'm using for the API endpoints.

E.G:

def my_funct():
   abort(400, 'Record not found') 

当调用my_funct时,我会在终端上打印找不到记录",但在API本身的响应中却不会,因为我总是收到500条消息错误.

When my_funct is called, I get the 'Record not found' printed on the terminal, but not in the response from the API itself, where I always get the 500 message error.

推荐答案

您有多种选择:

最基本的:

@app.route('/')
def index():
    return "Record not found", 400

如果要访问标题,则可以获取响应对象:

If you want to access the headers, you can grab the response object:

@app.route('/')
def index():
    resp = make_response("Record not found", 400)
    resp.headers['X-Something'] = 'A value'
    return resp

或者您可以使其更明确,不仅返回数字,还返回状态码对象

Or you can make it more explicit, and not just return a number, but return a status code object

from flask_api import status

@app.route('/')
def index():
    return "Record not found", status.HTTP_400_BAD_REQUEST

进一步阅读:

您可以在此处了解有关前两个信息的更多信息:关于响应(烧瓶快速入门)
第三个是:状态代码(《 Flask API指南》)

Further reading:

You can read more about the first two here: About Responses (Flask quickstart)
And the third here: Status codes (Flask API Guide)

这篇关于如何在Flask上返回400(错误请求)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆