我创建了一个简单的 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 端点的所有功能。
EG:
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
我喜欢使用
flask.Response
类:
from flask import Response
@app.route("/")
def index():
return Response(
"The response body goes here",
status=400,
)
flask.abort
是 werkzeug.exceptions.abort
的包装器,它实际上只是一个 helper 方法,可以更轻松地引发 HTTP 异常。在大多数情况下这很好,但对于 Restful API,我认为明确返回响应可能会更好。
这是我几年前编写的 Flask 应用程序的一些片段。它有一个 400 响应的示例
import werkzeug
from flask import Flask, Response, json
from flask_restplus import reqparse, Api, Resource, abort
from flask_restful import request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('address_to_score', type=werkzeug.datastructures.FileStorage, location='files')
class MissingColumnException(Exception):
pass
class InvalidDateFormatException(Exception):
pass
@api.route('/project')
class Project(Resource):
@api.expect(parser)
@api.response(200, 'Success')
@api.response(400, 'Validation Error')
def post(self):
"""
Takes in an excel file of addresses and outputs a JSON with scores and rankings.
"""
try:
df, input_trees, needed_zones = data.parse_incoming_file(request)
except MissingColumnException as e:
abort(400, 'Excel File Missing Mandatory Column(s):', columns=str(e))
except Exception as e:
abort(400, str(e))
project_trees = data.load_needed_trees(needed_zones, settings['directories']['current_tree_folder'])
df = data.multiprocess_query(df, input_trees, project_trees)
df = data.score_locations(df)
df = data.rank_locations(df)
df = data.replace_null(df)
output_file = df.to_dict('index')
resp = Response(json.dumps(output_file), mimetype='application/json')
resp.status_code = 200
return resp
@api.route('/project/health')
class ProjectHealth(Resource):
@api.response(200, 'Success')
def get(self):
"""
Returns the status of the server if it's still running.
"""
resp = Response(json.dumps('OK'), mimetype='application/json')
resp.status_code = 200
return resp
您可以返回一个元组,第二个元素是状态(400 或 500)。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Record not found", 400
if __name__ == '__main__':
app.run()
从Python调用API的示例:
import requests
response = requests.get('http://127.0.0.1:5000/')
response.text
# 'This is a bad request!'
response.status_code
# 400
我认为您正确使用了
abort()
功能。我怀疑这里的问题是错误处理程序捕获 400 错误,然后出错,从而导致 500 错误。有关 Flask 错误处理的更多信息,请参阅here。
作为示例,以下代码会将 400 更改为 500 错误:
@app.errorhandler(400)
def handle_400_error(e):
raise Exception("Unhandled Exception")
如果您没有进行任何错误处理,它可能来自
connexion
框架,尽管我不熟悉这个框架。
您可以简单地使用
@app.errorhandler
装饰器。
示例:
@app.errorhandler(400)
def your_function():
return 'your custom text', 400