我已经创建了一个简单的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-04 03:32:12
我认为您正确地使用了abort()
函数。我怀疑这里的问题是错误处理程序正在捕获400错误,然后找出导致500错误的错误。有关flask错误处理的更多信息,请参阅here。
例如,以下代码会将400错误更改为500错误:
@app.errorhandler(400)
def handle_400_error(e):
raise Exception("Unhandled Exception")
如果您没有做任何错误处理,那么它可能来自connexion
框架,尽管我不熟悉这个框架。
https://stackoverflow.com/questions/57664997
复制相似问题