我创建了一个简单的 flask 应用程序,我正在读取来自 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
进一步阅读:
您可以在这里阅读更多关于前两个的信息:About Responses ( flask 快速入门)
第三个在这里:Status codes ( flask API 指南)
关于python - 如何在 Flask 上返回 400(错误请求)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664997/