python - 如何在 Flask 上返回 400(错误请求)?
问题描述
我创建了一个简单的烧瓶应用程序,我正在读取来自 python 的响应:
response = requests.post(url,data=json.dumps(data), headers=headers )
data = json.loads(response.text)
现在我的问题是,在某些情况下,我想返回 400 或 500 消息响应。到目前为止,我正在这样做:
abort(400, 'Record not found')
#or
abort(500, 'Some error...')
这确实会在终端上打印消息:
但在 API 响应中,我不断收到 500 错误响应:
代码结构如下:
|--my_app
|--server.py
|--main.py
|--swagger.yml
server.py
这段代码在哪里:
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 端点的所有功能。
例如:
def my_funct():
abort(400, 'Record not found')
当my_funct
被调用时,我会Record not found
在终端上打印出来,但不会在 API 本身的响应中,在那里我总是会收到 500 消息错误。
解决方案
您有多种选择:
最基本的:
@app.route('/')
def index():
return "Record not found", 400
如果要访问标头,可以获取响应对象:
@app.route('/')
def index():
resp = make_response("Record not found", 400)
resp.headers['X-Something'] = 'A value'
return resp
或者你可以让它更明确,不仅仅是返回一个数字,而是返回一个状态码对象
from flask_api import status
@app.route('/')
def index():
return "Record not found", status.HTTP_400_BAD_REQUEST
进一步阅读:
推荐阅读
- javascript - 每行所有列的高度相等
- angular - 在Angular 2中使用HttpClient的http GET请求的默认超时是多少
- java - ReactorClientHttpConnector((
opt) -> {}) 未定义 - html - 如何调整表单的输入/输出增量
- php - 给出 HTTP 500 错误,Windows Laravel 5.7
- python - 相同的对象给出不同的值,取决于另一个对象是否被注释掉
- typescript - 如何验证 TypeScript 中的参数数量
- powershell - 将变量传递给函数
- reactjs - 如何从打字稿文件中导出 React 组件
- powershell - Powershell 在 VS Code 终端中的行为与普通终端不同