我已经创建了一个简单的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错误消息。
发布于 2019-09-03 23:42:11
您有多种选择:
最基本的:
@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 quickstart)
第三个是:Status codes (Flask API Guide)
发布于 2019-08-27 23:41:36
我喜欢使用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 method,它使得引发HTTP异常变得更容易。这在大多数情况下都很好,但对于restful API,我认为显式地返回响应可能会更好。
发布于 2019-08-29 07:16:05
下面是我几年前写的一个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
https://stackoverflow.com/questions/57664997
复制相似问题